Python Basics -Iterating Over Lists

abhinaya rajaram
Python in Plain English
4 min readJan 31, 2023

--

There are four collection data types in the Python programming language:

  • List is a collection that is ordered and changeable. It allows duplicate members.
  • Tuple is a collection that is ordered and unchangeable. It allows duplicate members.
  • Set is a collection that is unordered, unchangeable*, and unindexed. No duplicate members are allowed.
  • Dictionary is a collection that is ordered** and changeable. No duplicate members are allowed.

Lists are created using square brackets. Let’s see all the different ways to iterate over a list.

Method 1 → For loop to Square Numbers

Components:

  1. The original list over which our user-defined squared function will apply
  2. A user-defined function that will square numbers in the original list
  3. An empty list that will store the final squared output.
  4. A for-loop to iterate over the original list, apply the user defined function, append results to the empty list
def squared(num):
return num**2

# original list
num_list = [1,2,3,4,5,6]

# list that will contain the squared numbers
num_list_squared = []

# using a for loop to iterate over our num_list and create a new list with the squared values
for num in num_list:
num_list_squared.append(squared(num))

print(num_list_squared) # output is [1,4,9,16,25,36]

Method 2 → Using Map to Square Numbers

Components: Instead of a for loop to iterate over the items, we will use a “map” to apply the squared function automatically to the new list.

def squared(num):
return num**2

# original list
num_list = [1,2,3,4,5,6]

# using the map function to create this new list of squared values
num_list_squared = list(map(squared, num_list))

print(num_list_squared) # output is [1,4,9,16,25,36]

The map function returns an iterator called the map object. From here, we can cast the map object into a list .

The behind the scene activities are →The elements of the list[1,2,3] are passed as an argument to the square function and then we keep adding the output to the map object.

Method 3 → Lambda function to Square Numbers

To put it simply, the lambda function replaces the need for any user-defined functions and helps reduce our code length.

# original list
num_list = [1,2,3,4,5,6]

# using the map function to create this new list of squared values
num_list_squared = list(map(lambda x:x**2, num_list))

print(num_list_squared) # output is [1,4,9,16,25,36]

Method 4 → While Loop to square numbers

A while loop normally starts by defining a counter with an initial value and a condition based on that count that will allow the while loop to run when it’s true. We then change the counter inside the while in some way that at some point the condition becomes false.

counter = 0
while counter < len(num_list):
print(num_list[counter]**2)
counter += 1

Method 5 →Enumerate to square numbers

for index, value in enumerate(num_list):
print(value**2)
# Python program to illustrate
# enumerate function in loops
l1 = ["eat", "sleep", "repeat"]

# printing the tuples in object directly
for ele in enumerate(l1):
print (ele)

#Output is
(0, 'eat')
(1, 'sleep')
(2, 'repeat')

Method 6 → List transformation

List comprehension is basically creating lists based on existing iterables. It represents for and if loops with a simpler and more appealing syntax. We iterate over an iterable and do optionally perform an action on the items and then put them in a list. In some cases, we just take the items that fit a specified condition.

squared = [value**2 for value in num_list]
print(squared)

Method 7 → for and range together

The range() method basically returns a sequence of integers i.e. it builds/generates a sequence of integers from the provided start index up to the end index as specified in the argument list.

lst = [10, 50, 75, 83, 98, 84, 32]
for x in range(len(lst)):
print(lst[x])

Filter Method for Finding words that contain “Cat”

To make this work, you only need your original list and a function that returns true/false like outputs. The filter works exactly like the map function but has some differences. It stores only the “is True” element. In other words, only elements that satisfy the conditions of the user-defined function are stored in the filter object.

import re

# create a function that returns True if the element passed in Contains cat
def is_cat(strs):
match = re.findall('Cat', strs, flags=re.IGNORECASE)
return(match)


# original list of animals

list_of_animals = ['Cat', 'BobCat', 'Lion', 'Tomcat']

# new list that will contain only the items that have the word 'Cat' from list_of_animals
list_of_cats = list(filter(is_cat, list_of_animals))


print(list_of_cats)

#Output will be ['Cat', 'BobCat', 'Tomcat']

Using Filter & Lambda to filter for the word containing the term “Cat”


#Using lambda and filter together

t = list(filter((lambda x: re.findall(r'Cat', x,flags=re.IGNORECASE)),list_of_animals))
print(t)

#Output will be ['Cat', 'BobCat', 'Tomcat']

Conclusion

In this article. we have unveiled the various techniques to iterate a Python List.

More content at PlainEnglish.io.

Sign up for our free weekly newsletter. Follow us on Twitter, LinkedIn, YouTube, and Discord.

Build awareness and adoption for your tech startup with Circuit.

--

--