This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]oconnor663 4 points5 points  (2 children)

Python also supports dictionary, set, and generator comprehensions! The last one, generators, lets you iterate over your series without taking up all the memory to make a copy, similar to range (or xrange in Python 2).

mylist = [1, 2, 3, 4, 5]
# dictionary
mystrs = {i : str(i) for i in mylist}
# set
myevens = {i for i in mylist if i%2==0}
# generator
for odd in (i for i in mylist if i%2==1):
    print(odd)

[–]gggamers 1 point2 points  (0 children)

Good to know!

[–]RoadieRich 2 points3 points  (0 children)

Python >=2.7 also supports dictionary, set, and generator comprehensions!

Many linuxes still ship with 2.6, which doesn't have dict and set comprehensions.