Multidimensional Lists in Python
List elements can be not only strings and numbers, but also lists. In this case, such a list of lists is called multidimensional. In the following example, the list lst consists of three elements, which in turn are lists:
lst = [
['a', 'b', 'c'],
['d', 'e', 'f'],
['g', 'h', 'i'],
]
Depending on the nesting level, lists can be two-dimensional - a list of lists, three-dimensional - a list of lists of lists (and so on - four-dimensional, five-dimensional, etc.).
The list above is two-dimensional, since inside one list there are other sublists that do not contain other lists. To output any element from a two-dimensional list, you should write not one pair of square brackets, but two:
print(lst[0][1]) # 'b'
print(lst[1][2]) # 'f'
Multidimensional lists can also contain other iterables, such as dictionaries, sets, and tuples. Let's change the second element of the list to a dictionary:
lst = [
['a', 'b', 'c'],
{'d': 1, 'e': 2, 'f': 3},
['g', 'h', 'i'],
]
To get a dictionary element, you first need to get to the dictionary itself using the first square brackets. Then, in the second square brackets, write the dictionary key:
print(lst[1]['d']) # 1
Given a list:
lst = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
]
Derive from it the numbers 2, 4 and 8.
Given a list:
lst = [
['a', 'b'],
{'c': 1, 'd': 2},
{'e': 3, 'f': 4}
]
Derive from it the numbers 1, 3.