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.
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
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
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
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
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.
Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…
Given an integer A. Compute and return the square root of A. If A is…
Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…
A heap is a specialized tree-based data structure that satisfies the heap property. It is…
What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…