List/Dict comprehensions


List/Dict comprehensions are syntax constructions to ease the creation of a list/dict based on existing iterable. According to the 3rd edition of "Learning Python" list comprehensions are generally faster than normal loops but this is something that may change between releases. Examples:
 # 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}

No comments:

Post a Comment