In Python, there are several different ways to iterate through a list. Let’s examine every method for iterating over a list in Python and compare their performance.
Using For loop:
The “for” loop in Python is a way to run a repetitive block of code traversing over a sequence of any kind. For instance,
# code to iterate over a list
list = [1, 2, 3, 4, 5, 6, 7]
# Using for loop
for i in list:
print(i)
Output:
1
2
3
4
5
6
7
For loop and range():
It is used in case we want to employ the conventional for loop, which loops through numbers x and y. For example,
# code to iterate over a list
list = [1, 2, 3, 4, 5, 6, 7]
length = len(list)
# Iterating the index
# same as 'for i in range(len(list))'
for i in range(length):
print(list[i])
Output:
1
2
3
4
5
6
7
Using while loop:
For the while loop to work, one condition must be met. Till that condition is met, the loop iterates continuously. The loops are stopped as soon as it is determined to be false.
# code to iterate over a list
list = [1, 2, 3, 4, 5, 6, 7]
length = len(list)
i = 0
# Iterating using while loop
while i < length:
print(list[i])
i += 1
Output:
1
2
3
4
5
6
7
Iterate two Lists simultaneously :
Any quantity of list arguments can be passed to the zip() function. Let’s say there are two lists and you want to serially multiply each element of the first list by each element of the second list, save it to a third (empty) list, and so on.
list1 = [1, 2, 3, 4]
list2 = [5, 6, 7, 8]
reslt = []
for x, y in zip(list1, list2):
reslt.append(x*y)
print(reslt)
Output:
[5, 12, 21, 32]
Note: also read about Python Lists
Follow Me
Please follow me to read my latest post on programming and technology if you like my post.
https://www.instagram.com/coderz.py/
https://www.facebook.com/coderz.py
Staying up to the mark is what defines me. Hi all! I’m Rabecca Fatima a keen learner, great enthusiast, ready to take new challenges as stepping stones towards flying colors.
Leave a Comment