Skip to content

Instantly share code, notes, and snippets.

@xiaocong
Last active December 18, 2015 13:39
Show Gist options
  • Save xiaocong/5791279 to your computer and use it in GitHub Desktop.
Save xiaocong/5791279 to your computer and use it in GitHub Desktop.
# simple iteration
a = []
for x in range(10):
a.append(x*2)
# a == [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
# list comprehension
a = [x*2 for x in range(10)]
# dict comprehension
a = {x: x*2 for x in range(10)}
# a == {0: 0, 1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12, 7: 14, 8: 16, 9: 18
# set comprehension
a = {x**2 for x in range(10) if x % 2 == 0}
# a == set([0, 16, 4, 64, 36])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment