[Tutor] Syntax for list comps
Danny Yoo
dyoo at hashcollision.org
Thu Feb 4 00:29:15 EST 2016
On Wed, Feb 3, 2016 at 8:52 PM, Johan Martinez <jmartiee at gmail.com> wrote:
> Where can I find syntax for list comps? I am confused how/whether they are
> evaluated left-right or right-left. Consider following list flattening
> example:
>
> mx = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>
> [value for row in mx for value in row]
I read this as the following parts:
###################
mx = [
value # line 1
for row in mx # line 2
for value in row # line 3
]
###################
where I'm seeing three parts. Internally, I'm thinking that this is
going to work like the following code:
################################
mx = []
for row in mx: # from line 2
for value in row: # from line 3
mx.append(value) # from line 1
################################
where we represent the implicit "nesting" in the double loops in the
list comprehension as actual nesting here, and pieces get rearranged
from the list comprehension syntax into the above.
> That's a bit confusing syntax for me. Sorry if I am not clear in explaining
> it.
It is admittedly odd. I believe the syntax used for list
comprehensions is adopted from a kind of mathematical syntax that
mathematicians use for expressing sets of values.
For example, if we were to express the set of odd numbers as a
mathematician, we might say:
{ 2x + 1 | x ∈ N }
where N is extra fancy-looking, the '∈' is the math symbol for "in",
and the bar "|" is there just to distinguish the left side from the
right side. https://en.wikipedia.org/wiki/Set-builder_notation#Formal_set_builder_notation_sets
Now that you've seen what a mathematician writes to represent a set,
we can look back at Python list comprehensions: they bear a
resemblance to set builder notation. We don't have fancy symbols
ready on our keyboards, so we use for loop keywords to compensate. I
think that's the inspiration.
That being said, as soon as there are *two* loops nested in there, I
think list comprehensions are hard to read too. When they get nested
like that, I prefer to express them as the code with explicit list
construction and calls to append().
Hope that makes sense!
More information about the Tutor
mailing list