enumerate

enumerate is a very useful function to use with for loops. Let’s imagine the following situation:

  1. index_count = 0
  2. for letter in 'abcde':
  3. print("At index {} the letter is {}".format(index_count,letter))
  4. index_count+= 1

At index 0 the letter is a At index 1 the letter is b At index 2 the letter is c At index 3 the letter is d At index 4 the letter is e

Keeping track of how many loops you’ve gone through is so common, that enumerate was created so you don’t need to worry about creating and updating this index_count or loop_count variable

  1. # Notice the tuple unpacking!
  2. for i,letter in enumerate('abcde'):
  3. print("At index {} the letter is {}".format(i,letter))
  4. for i,letter in enumerate('abcde'):
  5. print("At index {} the letter is {}".f)

At index 0 the letter is a At index 1 the letter is b At index 2 the letter is c At index 3 the letter is d At index 4 the letter is e

zip

Notice the format enumerate actually returns, let’s take a look by transforming it to a list()

  1. mylist1 = [1,2,3,4,5]
  2. mylist2 = ['a','b','c','d','e']
  3. # This one is also a generator!
  4. zip(mylist1,mylist2)
  5. list(zip(mylist1,mylist2))

[(1, ‘a’), (2, ‘b’), (3, ‘c’), (4, ‘d’), (5, ‘e’)]

To use the generator, we could just use a for loop

  1. for item1, item2 in zip(mylist1,mylist2):
  2. print('For this tuple, first item was {} and second item was {}'.format(item1,item2))

For this tuple, first item was 1 and second item was a For this tuple, first item was 2 and second item was b For this tuple, first item was 3 and second item was c For this tuple, first item was 4 and second item was d For this tuple, first item was 5 and second item was e

map function

The map function allows you to “map” a function to an iterable object. That is to say you can quickly call the same function to every item in an iterable, such as a list. For example:

  1. def square(num):
  2. return num**2
  3. my_nums = [1,2,3,4,5]
  4. # To get the results, either iterate through map()
  5. # or just cast to a list
  6. list(map(square,my_nums))

[1, 4, 9, 16, 25]

filter function

The filter function returns an iterator yielding those items of iterable for which function(item) is true. Meaning you need to filter by a function that returns either True or False. Then passing that into filter (along with your iterable) and you will get back only the results that would return True when passed to the function.

  1. def check_even(num):
  2. return num % 2 == 0
  3. nums = [0,1,2,3,4,5,6,7,8,9,10]
  4. list(filter(check_even,nums))

[0, 2, 4, 6, 8, 10]