Python Loop through List Items

Python List – Loop through items

You can loop through the list of items in python using for loop, while loop or enumerate. We will go through each of them and their variations with examples.

In this tutorial, we shall go through some of the processes to loop through items in a list, with well detailed Python programs.

Lets recall that list is a collection of items that can be of different datatypes. For the examples mentioned below, we will consider the following list.

a = [52, 85, 41, 'sum', 'str', 3 + 5j, 6.8]

Loop List items using While Loop

In the following example, we will use Python While Loop to iterate through all the items in given list, and print them.

Python Program

a = [52, 85, 41, 'sum', 'str', 3 + 5j, 6.8]

i=0
while i<len(a):
	print(a[i])
	i+=1
Run

Output

52
85
41
sum
str
(3+5j)
6.8

Loop List items using index

Using Python For Loop with range, we can loop through the index and access the item in the list using this index.

Python Program

a = [52, 85, 41, 'sum', 'str', 3 + 5j, 6.8]

for i in range(len(a)):
	print(a[i])
Run

You can use this way if you need access to the index during the iteration.

Loop List items accessing list item directly

Or you can use the Python For Loop to directly access the elements itself rather than the index.

Python Program

a = [52, 85, 41, 'sum', 'str', 3 + 5j, 6.8]

for x in a:
	print(x)
Run

You can use this way, if you need access to the actual item itself rather than the index while through the iteration.

Loop List items using Enumerate

With enumerate() function, you can access both index and the item.

Python Program

a = [52, 85, 41, 'sum', 'str', 3 + 5j, 6.8]

for i,x in enumerate(a):
	print('element#',i,'is :',x)
Run

Output

element# 0 is : 52
element# 1 is : 85
element# 2 is : 41
element# 3 is : sum
element# 4 is : str
element# 5 is : (3+5j)
element# 6 is : 6.8

Summary

In this tutorial of Python Examples, we learned how to iterate through items in a list, with the help of well detailed example programs.