A looping is a special kind of structure that allows you to repeat an operation on a set of values. These set of values can be of a list, tuple or a dictionary. In this article, we’ll be going over how to loop over a list in python. There are many ways of iterate over lists in python, but the most simplest one is using loops such as while loop, for loop etc.
The loop statement is used to execute code multiple times. In the case of looping over a list, we will go through each element of the list and perform some action with it.
Methods To Loop Over A List In Python
In this article, we will cover the following methods:
- Using for loop to iterate over the list
- Looping over the list elements using while loop
- Access and perform any operation on the list elements in a single line using list comprehension
Method 01: For Loop
Using the for loop, we can access all the items of the list one by one. Consider an example in which you want to multiply the list elements by 2. Apply for loop on a list and on every iteration of for loop, an item for the list is multiplied by 2 and is printed on the output window.
input_list = [1,2,3,4,5,6,7,8,9,10] for i in range(0,len(input_list)): result = 2 * input_list[i] print("2 x " + str(input_list[i]) + " = " + str(result))
2 x 1 = 2 2 x 2 = 4 2 x 3 = 6 2 x 4 = 8 2 x 5 = 10 2 x 6 = 12 2 x 7 = 14 2 x 8 = 16 2 x 9 = 18 2 x 10 = 20
METHOD 02: WHILE LOOP
It is also possible to iterate the list using the while loop in Python just like for loop. Here in this example, we will create a counter function that increments the value by 1 on every iteration. Suppose you want the value to be incremented by 10 times.
def counter(count): return count + 1 i = 0; result = 0; while i < 10: result = counter(result) i=i+1 print("Result: ",result)
Method 03: List comprehension
List comprehension is another way to iterate over a list and it’s useful when you want to process each element of the list. The list comprehension makes use of for loops but execute whole program in a single line. Also the list comprehension makes the code more readable.
Suppose you have a list of students and you want to find whether the student with name David exists in the list or not. To find the name, you need to check all elements.
input_list = ["Nick", "Elizabeth", "John", "David", "Louis", "Kelin", "Ariana", "Susane"] search_item = [ input_list[i] for i in range(0,len(input_list)) if input_list[i] == "Louis"] print(search_item)
There are many ways to iterate over a list in Python. We hope that you found this article useful and add some new piece of information in your Python journey. Stay tuned for more articles.