Skip to content

Ways to Loop Through a List in Python Malli Spark By {Examples}

  • by

Python provides various ways to loop through the items or elements of a list. By using for loop syntax you can iterate any sequence objects (stringlisttupleset, range, or dictionary(dict)). A list contains a collection of values so, we can iterate each value present in the list using Python for loop or while loop in many ways.

In this article, I will explain looping through a list using for, range(), while, enumerate(), and list comprehension with examples.

 1. Quick Examples of Looping Through List

If you are in a hurry, below are some quick examples of the looping-through list.

# Quick examples of looping list

# Initialize list
courses = [“Python”, “Spark”, “pandas”, “Java”]

# Example 1: Iterate over list
# Using for loop
for item in courses:
print(item)

# Example 2: Using for loop and range()
for i in range(len(courses)):
print(courses[i])

# Example 3: Iterate over list
# Using a while loop
index = 0
while index < len(courses):
print(courses[index])
index = index + 1

# Example 4: Using enumerate() function
for index, value in enumerate(courses):
print(index, “:”, value)

# Example 5: Using list comprehension
[print(i) for i in courses]

# Example 6: Using map() function
def print_element(item):
print(item)
result = map(print_element, courses)
for _ in result:
pass

# Example 7: iterate over the NumPy array
# Using a for loop
courses_arr = np.array(courses)
for course in courses_arr:
print(course)

# Example 8: Using the iter function
# and the next function
iterator = iter(courses)
try:
while True:
element = next(iterator)
print(element)
except StopIteration:
pass

2. Looping Through List Using for Statement

You can loop through a list using a for loop in Python. This is the easiest way when we want to access element by element from a list. Let’s take a list of items and iterate it using for loop. For every iteration, we will print the item of the list to the console.

# Initialize list
courses = [“Python”, “Spark”, “pandas”, “Java”]
print(“Given list:”, courses)
print(“After iterating the list:”)

# Iterate over list
# Using for loop
for item in courses:
print(item)

Yields below output.

3. Loop Through List using for and range()

You can also loop through a list using for with range() function. The range() function returns a sequence of integers and starts from 0 and increments by 1(by default) and ends before an end number (n-1).

Use built-in function len(courses) to get the size of the list and use the size with range() function to get the list of values starting from 0 by incrementing 1 until the size of the list. To retrieve the value from the list use courses[x] within the body of for loop.

# Initialize list
courses = [“Python”, “Spark”, “pandas”, “Java”]
print(“Given list:”, courses)
print(“After iterating the list:”)

# Iterating the index
# Using for loop and range()
length = len(courses)
for i in range(length):
print(courses[i])

# Using for loop and range()
for i in range(len(courses)):
print(courses[i])

Yields the same output as above.

4. Using while Statement

You can also use a while to loop through the elements of a list in Python. The while in Python is used to iterate over a block of code as long as the test condition is true.

In the below example, inside the loop, the print() statement displays the value of the element at the current index from List courses, and then the index is incremented by 1. This process is repeated until the index is equal to the length of courses, at which point the loop terminates.

# Initialize list
courses = [“Python”, “Spark”, “pandas”, “Java”]
print(“Given list:”, courses)
print(“After iterating the list:”)

# Loopin through list
# Using a while loop
index = 0
while index < len(courses):
print(courses[index])
index = index + 1

Yields the same output as above.

5. Using enumerate() Function

You can also use the enumerate() function to loop through the list and get both the index and value of each item. For example, the enumerate() function returns a sequence of courses, where each list contains an index and a value from courses list. The for loops through over each list and unpacks the index and value into the variable’s index and value.

# Initialize list
courses = [“Python”, “Spark”, “pandas”, “Java”]
print(“Given list:”, courses)
print(“After iterating the list:”)

# Using enumerate() function
for index, value in enumerate(courses):
print(index, “:”, value)

Yields below output.

6. Looping Through List using List Comprehension

You can also use list comprehension to loop through over the courses list and print out each element. For example, list comprehension [print(i) for i in courses] creates a new list from the existing list. Then print each element on the console using the print() function.

# Initialize list
courses = [“Python”, “Spark”, “pandas”, “Java”]
print(“Given list:”, courses)
print(“After iterating the list:”)

# Using list comprehension
[print(i) for i in courses]

Yields below output.

# Output:
Given list: [‘Python’, ‘Spark’, ‘pandas’, ‘Java’]
After iterating the list:
Python
Spark
pandas
Java

7. Iterate over a List Using the map() Function

The map() function can be used to get each element of the list and apply some transformation to the element. In the below, first, initialized a list with four string elements. First defines a function print_element() that takes an argument item and prints it to the console.

Next, you can use the built-in map() function to apply the print_element function to each element in the courses list. The resulting iterator is assigned to the variable result. Finally, the code uses a for to iterate over the resulting result iterator. Since the print_element function already prints each element to the console, the loop simply passes over each element.

# Initialize list
courses = [“Python”, “Spark”, “pandas”, “Java”]
print(“Given list:”, courses)
print(“After iterating the list:”)

# Using map() function
def print_element(item):
print(item)
result = map(print_element, courses)
for _ in result:
pass

Yields the same output as above.

8. Iterate over a List Using NumPy

Alternatively, we can loop through the list using NumPy. First, initialize a list then convert it into a NumPy array using the np.array() function. This allows us to use NumPy functions to work with the list.

import numpy as np

# initialize a list
courses = [“Python”, “Spark”, “pandas”, “Java”]
print(“Given list:”, courses)
print(“After iterating the list:”)

# iterate over the NumPy array
# Using a for loop
courses_arr = np.array(courses)
for course in courses_arr:
print(course)

Yields the same output as above.

9. Using the Iter Function and the Next Function

You can create an iterator object using the iter() function, which takes an iterable object (in this case, the courses list) as an argument. Then, it uses a while loop to iterate over the elements of the iterator by calling the next() function on the iterator object in each iteration.

The next() function returns the next element of the iterator, and the loop continues until there are no more elements to return. If there are no more elements to return, the next() function raises a StopIteration exception, which is caught by the try-except block and the loop terminates.

# Initialize list
courses = [“Python”, “Spark”, “pandas”, “Java”]
print(“Given list:”, courses)
print(“After iterating the list:”)

# Using the iter function
# and the next function
iterator = iter(courses)
try:
while True:
element = next(iterator)
print(element)
except StopIteration:
pass

Yields the same output as above.

10. Conclusion

In conclusion, You can loop through a Python List by using for, range(), while, enumerate(), and list comprehension, I have explained all these methods with examples. You can use any of these implementations as per your need.

Happy Learning !!

 Python provides various ways to loop through the items or elements of a list. By using for loop syntax you can iterate any sequence objects (string, list, tuple, set, range, or dictionary(dict)). A list contains a collection of values so, we can iterate each value present in the list using Python for loop or while loop in many ways. In this article, I will  Read More Python, Python Tutorial, Python For Loop Examples, Python List Examples 

Leave a Reply

Your email address will not be published. Required fields are marked *