Table of Contents
ToggleLooping through list items in Python refers to iterating over each element within a list. We do so to perform the desired operations on each item. These operations include list modification, conditional operations, string manipulation, data analysis, etc.
Python provides various methods for looping through list items, with the most common being the for loop. We can also use the while loop to iterate through list items, although it requires additional handling of the loop control variable explicitly.
For LoopA for loop in Python is used to iterate over a sequence (like a list, tuple, dictionary, string, or range) or any other iterable object. It allows you to execute a block of code repeatedly for each item in the sequence.
lst = [25, 12, 10, -21, 10, 100]
for num in lst:
print(num, end=' ')
Output:
25 12 10 -21 10 100
While LoopA while loop in Python is used to repeatedly execute a block of code as long as a specified condition evaluates to True.
my_list = [1, 2, 3, 4, 5]
index = 0
while index < len(my_list):
print(my_list[index])
index += 1
Output:
1
2
3
4
5
We can loop through list items using an index by iterating over a range of indices corresponding to the length of the list and accessing each element using the index within the loop.
lst = [25, 12, 10, -21, 10, 100]
for i in range(len(lst)):
print(f"lst[{i}]:", lst[i])
Output:
lst[0]: 25
lst[1]: 12
lst[2]: 10
lst[3]: -21
lst[4]: 10
lst[5]: 100
A list comprehension in Python is a concise way to create lists by applying an expression to each element of an iterable.
numbers = [1, 2, 3, 4, 5]
squared_numbers = [num ** 2 for num in numbers]
print(squared_numbers)
Output:
[1, 4, 9, 16, 25]
enumerate() FunctionThe enumerate() function in Python is used to iterate over an iterable object while also providing the index of each element.
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
print(index, fruit)
Output:
0 apple
1 banana
2 cherry
