Python | Nested List Comprehension

List Comprehension is a beautiful feature of Python. But most of the Python beginners (like me) get confused when it comes to nested list comprehension. So I thought to write few lines of Python code that might help you to understand it better.

Can you figure out the output of the following statement?
[(x, y) for x in range(1, 5) for y in range(0, x)]

Here is the output:
[(1, 0), (2, 0), (2, 1), (3, 0), (3, 1), (3, 2), (4, 0), (4, 1), (4, 2), (4, 3)]

If you could figure it out correctly, you don't need to read the rest of the post.

Now, look at the following code


>>> for x in range(1, 5):
...     for y in range(0, x):
...         print x, y
...
1 0
2 0
2 1
3 0
3 1
3 2
4 0
4 1
4 2
4 3
>>>


This is actually same as [(x, y) for x in range(1, 5) for y in range(0, x)]

Now think about it, experiment with your own ideas and things will be clear. :)

Comments

Unknown said…
How can I use this method to get the output shown, using a csv. file input of x and y columns?

Popular posts from this blog

Strip HTML tags using Python

lambda magic to find prime numbers

Convert text to ASCII and ASCII to text - Python code