[Tutor] Nested list comprehensions
Alan Gauld
alan.gauld at yahoo.co.uk
Sun Oct 18 07:42:42 EDT 2020
On 18/10/2020 06:39, Manprit Singh wrote:
> Just need to know , if my understanding is correct or not ?
Its hard to know what your understanding is from this example.
Thee are multiple ways to write nested comprehensions.
This example is really just one comprehension embeded
in another. A comprehension is:
[<expression> <for loop> <condition>]
The expression can be any valid Python expression, which
obviously includes a comprehension. The condition likewise
can be any Python expression that evaluates to a thruth-like
value - so that too could be a comprehension. And the for
loop can have multiple elements which is also referred to
as a nested comprehension.
And you can nest comprehensions to an arbitrary number
of levels, resulting in code that is completely
incomprehensible.
Does your understanding encompass all those variety of
nested comprehension?
> 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)
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list