Lists in Python. Iteration and Filtering | by Sadrach Pierre, Ph.D. | Towards Data Science

In python, a list is delimited by the characters ‘[]’. The characters ‘[]’, alone, designate an empty list. An example of a list is [‘Guido van Rossum’, ‘Bjarne Stroustrup’, ‘James Gosling’], which is a list containing three string instances. Further, the elements of a list can be arbitrary objects (including None). For example, you can have the following list: [8200000, ‘Python’, None]. Lists are one of the most used containers in python and are central to data structures and algorithms in computer science.
In this post, we will discuss how to iterate through and filter lists using three different looping constructs in python. We will discuss how to use ‘while loops’, ‘for loops’, and ‘index-based for loops’ for list iteration. We will also give an example of list comprehension in python for list filtering.
While loops allow us to repeat an action based on repeated testing of a condition. In other words, any time you need a program to keep doing something until a condition is met, ‘while loops’ are useful.
For our example, we will consider the problem of filtering a list of songs based on the song writer. Suppose we have a list of tuples of songs and writers from the first side of the album Abbey Road, by The Beatles:
abbey_road = [('Come Together', 'Lennon'), ('Something', 'Harrison'), ('Maxwell's Silver Hammer', 'McCartney'), ('Oh! Darling!','McCartney'), ('Octopus's Garden', 'Starr'), ('I Want You', 'Lennon')]
We can iterate over the list of tuples using a ‘while loop’:
j = 0 #initialize the index while j < len(abbey_road):    print(abbey_road[j])     j+=1 #advanced the index 
Here, the ‘while loop’ condition is that the index we advance after each iteration must be less than the length of the list.
To filter the list of tuples based on the song writer, we can apply an additional condition. Suppose we want to remove songs by Paul McCartney. We can do the following:
j = 0while j < len(abbey_road):     if abbey_road[j][1] != "McCartney":             print(abbey_road[j])            j+=1
We can do the same for the other song writers as well. I encourage you to give it a shot! Now let’s move on to ‘for loops’.
We will be using ‘for loops’ to solve the same problem of list filtering. To start, let’s iterate over the ‘abbey_road’ list and print each element:
for song, artist in abbey_road:    print((song, artist))
As you can see, this is a bit easier to read. This construct allows us to define names for the elements we are iterating over, which helps with code readability. Let’s filter out songs by Lennon:
for song, artist in abbey_road:    if artist != "Lennon":        print((song, artist))
Try modifying the condition to filter by song or a different string value for the artist. Let’s move on the ‘index-based for loops’.
For this example, we will iterate through the ‘abbey_road’ list using ‘index-based for loops’.
for i in range(len(abbey_road)):    print((abbey_road[i][0], abbey_road[i][1]))
Which gives us the expected result. Let’s apply the filter for songs written by Harrison:
for i in range(len(abbey_road)):    if abbey_road[i][1] != "Harrison":        print((abbey_road[i][0], abbey_road[i][1]))
As you can see, this for loop construct is not as readable as the previous construct. Now let’s move on to the last example, list comprehension.
For this last example, we will use list comprehension to filter the ‘abbey_road’ list. Let’s filter out songs by “Lennon” again:
filtered_list = [(song, artist) for song, artist in abbey_road if artist != "Lennon"]print(filtered_list)
In my opinion, this is the most readable and compact way to filter a list in python.
To summarize, in this post we discussed list objects in python. We went over three ways in which we can iterate over and filter the elements of a list in python. We also gave an example of list filtering using list comprehension. I encourage you to play around with the methods of filtering and iterating through lists. For example, you can define a new list and apply the methods above or try changing the conditions for filtering in each example. I hope you found this post interesting/useful. The code in this post is available on GitHub. Thank you for reading!