[Tutor] Nested list comprehensions

Mats Wichmann mats at wichmann.us
Sun Oct 18 08:24:25 EDT 2020


On 10/17/20 11:39 PM, Manprit Singh 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)


To the other replies let me add a thought: when you build an object
using a comprehension, you are committing to creating the whole thing
there as that line runs.  For most of what we do - *especially* in small
artificial learning examples - that's fine, and just what you want. But
when you're nesting to initialize a multi-dimensional array, it can
easily get big, and slow.  Try giving your sample code some bigger
numbers, say 50,000 x 50,000 - you'll notice a considerable delay as it
creates. Maybe you didn't need to fully allocate all of that up front?
Python has ways of deferring the computation - range is an example -
it's a lazy iterable that produces its values when asked for them -
though when used as above, you lose the effect of the lazyness since you
ask for all the values in a loop.  The map function, while much less
popular than it used to be since comprehensions became "the thing",
returns an iterator, another kind of "just-in-time" object.


More information about the Tutor mailing list