Nested list indexing Python

A list in Python may contain any objects as its elements, including other lists — they are called nested lists. Here are some examples of nested lists:

Accessing elements of nested lists

Like with regular lists, elements of a nested list can be accessed by indexes. Note that the nested list still counts as a single element in its parent list.

In this example, we obtain the second element of numbers by index 1. This element is the nested list [2, 3]. Then we print the second element of nested_numbers by index 1. This element is 3.

It is also possible to access an element of a nested list without an additional variable using a sequence of square brackets.

Basically, we go deeper from the outer list to the innermost when indexing. Naturally, if we ask for an element at the level that doesn’t exist, we’ll get an error:

Just like when we try accessing an element that doesn’t exist at the level that does exist:

Matrices

Nested lists are a convenient way to represent a matrix. For example, the matrix

might be represented as:

Note that in such a list lengths of all nested lists must be the same, and they are equal to the dimension of the matrix.

When we want to extract an element from the matrix, e.g. element M[1][2] = 6, the first index selects the row, and the second index selects the column. However, as you know, it differs from mathematical representation in that numbering here starts from zero, rather than from one.

Nested list comprehension

To iterate over nested lists, we can use nested list comprehensions. It is basically a combination of two or more list comprehensions and it is quite similar to nested “for” loops. To illustrate basic syntax for this kind of comprehension, let’s consider an example.

Imagine a school as a list of classes that are, in turn, lists of students [their names].

If you want to create a list of all students in all classes without the list comprehension it would look like this:

Alternatively, we can also use a comprehension with a double for loop, then it would look like this:

In both cases the result is going to be the same:

In this case, the order of the for loops are the same as in the notation with indentation: first the outer loop, and then the inner loop.

However, such a method may be less clear than the one without list comprehension, especially in cases when we need to use more than two for loops: it can make the code unreadable and counter-intuitive.

Consider the following line of code:

It’s not that easy to understand what the created matrix will look like. Compare to when we will put it this way:

It is much more readable, and now it is clear what the matrix will look like this:

It’s important to bear in mind that shorter code does not imply a better one, so you shouldn’t misuse list comprehension when working with nested lists.

Summary

To sum up, lists as such are a very useful type of container in Data Structures, and now you know how to store multiple inner lists inside an outer one, reach them, represent matrices with them, and use nested list comprehensions.

Content Inspired by Jetbrains

List Comprehensions are one of the most amazing features of Python. It is a smart and concise way of creating lists by iterating over an iterable object. Nested List Comprehensions are nothing but a list comprehension within another list comprehension which is quite similar to nested for loops.

Let’s take a look at some examples to understand what nested list comprehensions can do:

Example 1:

I want to create a matrix which looks like below: matrix = [[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]

The below code uses nested for loops for the given task:

matrix = []

for i in range[5]:

    matrix.append[[]]

    for j in range[5]:

        matrix[i].append[j]

print[matrix]

Output:

[[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]

The same output can be achieved using nested list comprehension in just one line:

matrix = [[j for j in range[5]] for i in range[5]]

print[matrix]

Output: [[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]

Explanation:

The syntax of the above program is shown below:

[expression for i in range[5]] –> which means that execute this expression and append its output to the list until variable i iterates from 0 to 4.

For example:- [i for i in range[5]] –> In this case, the output of the expression is simply the variable i itself and hence we append its output to the list while i

iterates from 0 to 4.

Thus the output would be –> [0, 1, 2, 3, 4]

But in our case, the expression itself is a list comprehension. Hence we need to first
solve the expression and then append its output to the list.

expression = [j for j in range[5]] –> The output of this expression is same as the
example discussed above.

Hence expression = [0, 1, 2, 3, 4].

Now we just simply append this output until variable i iterates from 0 to 4 which would be total 5 iterations. Hence the final output would just be a list of the output of the

above expression repeated 5 times.

Output: [[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]

Example 2:

Suppose I want to flatten a given 2-D list: matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] Expected Output: flatten_matrix = [1, 2, 3, 4, 5, 6, 7, 8, 9]

This can be done using nested for loops as follows:

matrix = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]

flatten_matrix = []

for sublist in matrix:

    for val in sublist:

        flatten_matrix.append[val]

print[flatten_matrix]

Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]

Again this can be done using nested list comprehension which has been shown below:

matrix = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]

flatten_matrix = [val for sublist in matrix for val in sublist]

print[flatten_matrix]

Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]

Explanation:

In this case, we need to loop over each element in the given 2-D list and append it to another list. For better understanding, we can divide the list comprehension into

three parts:

flatten_matrix = [val for sublist in matrix for val in sublist]

The first line suggests what we want to append to the list. The second line is the
outer loop and the third line is the inner loop.

‘for sublist in matrix’ returns the sublists inside the matrix one by one which would be:

[1, 2, 3], [4, 5], [6, 7, 8, 9]

‘for val in sublist’ returns all the values inside the sublist.

Hence if sublist = [1, 2, 3], ‘for val in sublist’ –> gives 1, 2, 3 as output one by one.

For every such val, we get the output as val and we append it to the list.

Example 3:

Suppose I want to flatten a given 2-D list and only include those strings whose lengths are less than 6:

planets = [[‘Mercury’, ‘Venus’, ‘Earth’], [‘Mars’, ‘Jupiter’, ‘Saturn’], [‘Uranus’, ‘Neptune’, ‘Pluto’]]

Expected Output: flatten_planets = [‘Venus’, ‘Earth’, ‘Mars’, ‘Pluto’]

This can be done using an if condition inside a nested for loop which is shown below:

planets = [['Mercury', 'Venus', 'Earth'], ['Mars', 'Jupiter', 'Saturn'], ['Uranus', 'Neptune', 'Pluto']]

flatten_planets = []

for sublist in planets:

    for planet in sublist:

        if len[planet] < 6:

            flatten_planets.append[planet]

print[flatten_planets]

Output: ['Venus', 'Earth', 'Mars', 'Pluto']

This can also be done using nested list comprehensions which has been shown below:

planets = [['Mercury', 'Venus', 'Earth'], ['Mars', 'Jupiter', 'Saturn'], ['Uranus', 'Neptune', 'Pluto']]

flatten_planets = [planet for sublist in planets for planet in sublist if len[planet] < 6]

print[flatten_planets]

Output: ['Venus', 'Earth', 'Mars', 'Pluto']

Explanation:

This example is quite similar to the previous example but in this example, we just need an extra if condition to check if the length of a particular planet is less than

6 or not.

This can be divided into 4 parts as follows:

flatten_planets = [planet for sublist in planets for planet in sublist if len[planet] < 6]

Article Tags :

Practice Tags :

Video liên quan

Chủ Đề