Categories: python

Iterate over a list in Python

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

Recent Posts

Generate Parenthesis | Intuition + Code | Recursion Tree | Backtracking | Java

Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…

2 months ago

Square Root of Integer

Given an integer A. Compute and return the square root of A. If A is…

1 year ago

Build Array From Permutation

Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…

1 year ago

DSA: Heap

A heap is a specialized tree-based data structure that satisfies the heap property. It is…

1 year ago

DSA: Trie

What is a Trie in DSA? A trie, often known as a prefix tree, is…

1 year ago

Trees: Lowest Common Ancestor

What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…

1 year ago