[Tutor] Nested list comprehensions

Manprit Singh manpritsinghece at gmail.com
Sun Oct 18 09:08:43 EDT 2020


Dear sir ,

I realized my mistake, the question is incomplete . But With the previous
replies i have got clarity about nested list comprehensions too . See when
we go through Python docs for nested list comprehension, the example
given(Transpose of a matrix) really is quite difficult to understand(less
readable) . So Someone like me who is reading this example given in Python
docs will be forced to think  - what is the appropriate use case of nested
list comprehensions . Hope I am right ?

Example given in Python docs is given below :

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

To transpose rows and columns :

[[row[i] for row in matrix] for i in range(4)]

See this is not a readable solution. When i read it for the first
time, i too didn't get what's going with this comprehension. So
clearly i  will not
prefer using it.

So the question comes to explain the valid and readable use case for
nested list comprehension . For that i quickly wrote an example to
create a 2D list

with for loop and with list comprehension . which are as follows :


def two_d(r, c, e):
    l1 = []
    for i in range(r):
        l2 = []
        for j in range(c):
            l2.append(e)
        l1.append(l2)
    return l1


two_d(3, 5, 8)
Out[4]: [[8, 8, 8, 8, 8], [8, 8, 8, 8, 8], [8, 8, 8, 8, 8]]

Obviously this for loop based solution may be disliked by most of the
people , hance i tried to write it in list comprehension form as
follows and

found it more convenient , which is given below :

def two_d(row, col, ele):
    return [[ele for _ in range(col)] for _ in range(row)]


x = two_d(3, 5, 8)
print(x)

and got the same answer . See here the nested comprehension is quite clear
to read, and hence i wrote a question but unfortunately i wasn't able to
express
myself fully . So comparing my own example with the example given in the
Python documentation, i feel my example is readable one and can be used to
explain the valid use case of  nested list comprehension . I hope my
question is clear now .

Regards
Manprit Singh




On Sun, Oct 18, 2020 at 11:09 AM Manprit Singh <manpritsinghece at gmail.com>
wrote:

> Dear sir ,
>
> While reading about nested list comprehensions, i have tried to write an
> example of making a 2D list with m rows and n columns with each element of
> list equals e.
> Just need to know , if my understanding is correct or not ?
>
> def two_d(row, col, ele):
>     return [[ele for _ in range(col)] for _ in range(row)]
>
> m = int(input("Enter no of rows"))
> n = int(input("Enter no of columns"))
> e = int(input("Enter the element to be placed inside list'))
> two_d(m, n, e)
>
> Regards
> Manprit Singh
>


More information about the Tutor mailing list