How to extract and filter the content of an iterator in Python

Let’s say that you have an iterator and you need to list all the containing elements within it. In order to do that you can use the enumerate() function which will take an iterable object and return a list of tuples (count + value).

>>> bikes = ['Honda', 'Yamaha', 'Suzuki']
>>> bike_enum = enumerate(bikes)
>>> next(bike_enum)
(0, 'Honda')
>>> next(bike_enum)
(1, 'Yamaha')
>>> next(bike_enum)
(2, 'Suzuki')

Note:
The count begins with zero. It can be changed using the start parameter.

bikes = ['Honda', 'Yamaha', 'Suzuki']
>>> bike_enum_2 = enumerate(bikes, start = 4)
>>> next(bike_enum_2)
(4, 'Honda')
>>> next(bike_enum_2)
(5, 'Yamaha')
>>> next(bike_enum_2)
(6, 'Suzuki')

You may want all these values to be put in a list so you can do some further processing.

>>> bikes = ['Honda', 'Yamaha', 'Suzuki']
>>> bikes_list = list(enumerate(bikes))
>>> bikes_list
[(0, 'Honda'), (1, 'Yamaha'), (2, 'Suzuki')]

Now, you might want to filter the list and extract only the items that return True based on your filtering criteria.

>>> bikes = ['Honda', 'Yamaha', 'Suzuki']
>>> filtered_list = [f for f in bikes if 'a' in f]
>>> filtered_list
['Honda', 'Yamaha']
>>> another_filtered_list = [x for x in bikes if 'H' in x]
>>> another_filtered_list
['Honda']

Or you can write a piece of code as shown below which is longer code but it might be a little bit more clearer for some people.

>>> bikes = ['Honda', 'Yamaha', 'Suzuki']
>>> filtered_bikes = []
>>> for b in bikes:
... 	if 'a' in b:
... 		filtered_bikes.append(b)
... 
>>> filtered_bikes
['Honda', 'Yamaha']

Leave a Reply