Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save DavidWittman/3184205 to your computer and use it in GitHub Desktop.
Save DavidWittman/3184205 to your computer and use it in GitHub Desktop.
Nested list comprehensions in Python

Nested list comprehensions in Python

For some reason or another, I'm always second guessing myself when writing nested list comprehensions. Here's a quick example to clarify what's going behind the scenes:

>>> words = ["foo", "bar", "baz"]
>>> [letter for word in words for letter in word]
['f', 'o', 'o', 'b', 'a', 'r', 'b', 'a', 'z']

In other words, the for loops are nested from left-to-right. If we just wanted to print the values in the above example, we could replace the nested list comprehensions with the following for statements:

>>> for word in words:
...   for letter in word:
...     print letter
... 
f
o
o
b
a
r
b
a
z

Hopefully this will clarify nested list comprehensions for future me.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment