Double Iteration in List Comprehension
Here’s something I didn’t know possible in Python: iteration over more than one iterable in a list comprehension:
Cool, isn’t it? It’s equivalent to the following snippet:
It also supports both “if” statements and referencing the outer iterator from the inner one, like so:
This is equivalent to the snippet:
The thing you should notice here, is that the outer loop is the first ‘for’ loop in the list comprehension. This was a little confusing for me at first because when I nest list comprehensions it’s the other way around.
To read more about this feature, check out this StackOverflow thread or the Python Manual.Discuss this post at the comment section below.
Follow me on Twitter , Facebook or Google+