4. Building lists question

evens_to_50 = [i for i in range(51) if i % 2 == 0]

what why theres "i" in front of the list ''[i for i in range...]"



Say we need to obtain a list of all the integers in a sequence and then square them:

a_list = [1, ‘4’, 9, ‘a’, 0, 4]

squared_ints = [ e**2 for e in a_list if type(e) == types.IntType ]

print squared_ints
# [ 1, 81, 0, 16 ]

take look at this image

  • The iterator part iterates through each member e of the input
    sequence a_list.
  • The predicate checks if the member is an integer.
  • If the member is an integer then it is passed to the output
    expression, squared, to become a member of the output list.

You can read more on it here
Click here to article