How Can We Help?
Introduction:
In this tutorial, we are going to explain how to use Python iterate list by using for loops with basic syntax and many examples for better understanding.
Python iterate list operators (for loops & while loop) is used to iterate element of list.
Syntax:
for var in (list_variable_name) :
(for block)
Input Parameters:
- var : the variable that will hold each value of given list.
- list_variable_name : The lists that we want to iterate through it.
Using for loops Example (1)
myList = [1,2,3,4]
for var in myList:
print("Index of Element :", myList.index(var) , " - Element of list:",var)
Output of example 1
Index of Element : 0 – Element of list: 1
Index of Element : 1 – Element of list: 2
Index of Element : 2 – Element of list: 3
Index of Element : 3 – Element of list: 4
In the above Example, using iteration, we fetched the index of each element in the list and the element of list (1,2,3,4) and print them together in separate lines.
Using for loops and range Example (2)
# example list
myList = [1, 2, 3, 4]
# getting length of list
lengthOfmyList = len(myList)
# Iterating the index
for var in range(lengthOfmyList):
print(myList[var])
Output of example 2
1
2
3
4
In the above Example, using for loops with rang, we iterate through the rang of our list “myList” then print each value of the list in a separate line.
Using for loops and range Example (3)
# example list
myList = [1, 2, 3, 4, 9, 10, 8]
# Getting length of list
lengthOfmyList = len(myList)
i = 0
# Iterating through the list using while loop
while i < lengthOfmyList:
print(myList[i])
i += 1
Output of example 3
1
2
3
4
9
10
8
In the above Example, using iteration with while loop, we fetched the element of list (1,2,3,4,9,10,8) and print them together in separate lines.
In this tutorial, you have learned how to iterate through list elements in python.
If you have an inquiry or doubt don’t hesitate to leave them in comment. we are waiting your feedback.But remember to understand the concept very well, you need to practice more.
Hopefully, it was clear and concise.
Similar Python operators:
- Concatenation(‘+’) : It adds two lists.
- Membership(‘in’ & ‘not in’) : It returns True , if given element is present in list otherwise returns False.
- Repetition(‘*’) : It repeats element of list.
Python tutorials list:
- Python tutorials list : access all python tutorials.