In this section, we will learn how to iterate through the elements of a List in Python.
Python Iterate List: How to Iterate Through a List in Python?
A List in Python is iterable! That means we can use loops like `while` and `for` in order to access the elements of the list and run any necessary operation on them.
Now let’s see how to loop through a list using the for loop:
Python for in List
When using the `for-in` loop, it goes through the elements of a list and takes them one by one until the last element in the list.
Basically, using the `for-in` loop, there’s no need to use the pair of brackets `[]` if the iterable object that the loop needs is the list itself.
Example: Python Loop through List via for Loop
list1 = ["John","Jack","Omid","Ellen","Elon","Ian","Jame","Richard"] for element in list1: print(element)
Output:
John Jack Omid Ellen Elon Ian Jame Richard
Python for Loop with Index Number:
The problem that the last example has is that we can’t change the elements of the list if needed! All we got was just the elements of the list! Basically, using this technique, we can only read the elements of the list and not modify them!
Now if we want to be able to modify the elements of the list while iterating through them, one option would be to use the `len()` and `range()` functions.
Basically, we can use the `range()` function to produce a sequence of number, use the `len()` function to get the size of the target list and put that as the argument of the `range()` function in order to get accurate sequence of numbers and then finally use the produced sequence as the value in the pair of brackets `[]` in order to access the elements of the target list (either modify or get the values in the list).
Example: Python with for Loop and Index Number
list1 = ["John","Jack","Omid","Ellen","Elon","Ian","Jame","Richard"] for index in range(len(list1)): list1[index] = 0 print(list1)
Output:
[0, 0, 0, 0, 0, 0, 0, 0]
Iterate Through List Python via while Loop Example:
list1 = ["John","Jack","Omid","Ellen","Elon","Ian","Jame","Richard"] num = 0; size = len(list1) while num<size: list1[num] = 0 num +=1 print(list1)
Output:
[0, 0, 0, 0, 0, 0, 0, 0]