[Tutor] List Comprehension Syntax
Mitya Sirenef
msirenef at lightbird.net
Sun Dec 23 09:14:21 CET 2012
On 12/23/2012 02:48 AM, Mario Cacciatore wrote:
> Hey everyone,
>
> I am having a very hard time understanding the list comprehension
syntax. I've followed the docs and could use some guidance from the fine
folks here to supplement my findings. If someone wouldn't mind replying
back with an example or two, with some explanation of each part I'd
appreciate it.
Hi Mario, here are some examples (using python3 but very similar in py2.7):
>>> L = range(20)
>>> [x for x in L]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>> [x for x in L if x<=10]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> [(x,x) for x in L]
[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8),
(9, 9), (10, 10), (11, 11), (12, 12), (13, 13), (14, 14), (15, 15), (16,
16), (17, 17), (18, 18), (19, 19)]
>>> [x*2 for x in L]
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38]
>>> [(x, x*3) for x in L if x<=10]
[(0, 0), (1, 3), (2, 6), (3, 9), (4, 12), (5, 15), (6, 18), (7, 21), (8,
24), (9, 27), (10, 30)]
>>> def strmul(x): return str(x), x*2
...
>>> [strmul(x) for x in L if x<=10]
[('0', 0), ('1', 2), ('2', 4), ('3', 6), ('4', 8), ('5', 10), ('6', 12),
('7', 14), ('8', 16), ('9', 18), ('10', 20)]
Hope this helps!
--
Lark's Tongue Guide to Python: http://lightbird.net/larks/
More information about the Tutor
mailing list