List comprehension
Steve D'Aprano
steve+python at pearwood.info
Fri Dec 30 19:37:55 EST 2016
On Sat, 31 Dec 2016 06:37 am, Jason Friedman wrote:
> $ python
> Python 3.6.0 (default, Dec 26 2016, 18:23:08)
> [GCC 4.8.4] on linux
> Type "help", "copyright", "credits" or "license" for more information.
>>>> data = (
> ... (1,2),
> ... (3,4),
> ... )
>>>> [a for a in data]
> [(1, 2), (3, 4)]
>
> Now, this puzzles me:
>
>>>> [x,y for a in data]
> File "<stdin>", line 1
> [x,y for a in data]
> ^
> SyntaxError: invalid syntax
>
> I expected:
> [(1, 2), (3, 4)]
Why would you expect that? I would expect the global variables x and y, or
if they don't exist, a NameError:
py> a = (1, 2)
py> x, y
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined
Python has no magic that "x and y mean the first two items of a".
Instead, you get a syntax error because the syntax is ambiguous:
[x,y for a in data]
looks like a list
[x, y]
except the second item is a syntax error "y for a in data". So let's fix the
syntax error:
py> data = [(1, 2), (3, 4)]
py> [a for a in data]
[(1, 2), (3, 4)]
py> [(x, y) for a in data]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <listcomp>
NameError: name 'x' is not defined
Okay, let's create global variables x and y:
py> x = 98
py> y = 99
py> [(x, y) for a in data]
[(98, 99), (98, 99)]
No surprises there. How about this instead:
py> [(x, y) for (x, y) in data]
[(1, 2), (3, 4)]
That's better!
--
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.
More information about the Python-list
mailing list