Iterate through the list in Python
One of the six basic data types of the Python computer language is the list. You must be familiar with the methods and functions that deal with lists in order to use Python efficiently. And in this essay, we'll explain why.
Multiple elements can be stored in a single variable in Python by using lists. A single Python iterate list can also contain members of different data kinds. Lists can contain additional lists since they can be nested, just like an array in other computer languages.
There are several different ways to iterate through lists in Python, and each one has advantages and disadvantages. In this post, we'll examine the iteration methods for Python lists and provide an illustration for each one.
In Python, There Are Seven Different Ways to Iterate through a List:
1. A Basic for Loop
One of the easiest techniques to iterate through a list and any other sequence is to use a Python for loop (e.g.SETS, TUPLES, OR DICTIONARIES).
Programmers should be aware of the versatility of Python for Loops because it is a potent tool. They can be used to have the loop's statements run once for each element in a list. For instance:
Code:
fruits_list = ["Orange", "Grape", "Banana", "Apple", "Cherry", "Fig", "Mango"]
for frt in fruits_list:
print(frt)
Output:
[Running] python -u "d:\Programming\Python\test.py"
Orange
Grape
Banana
Apple
Cherry
Fig
Mango
[Done] exited with code=0 in 0.168 seconds
Each item on the list has been printed here by the for loop. In the other words, the loop has executed the print() method four times, printing the name of a fruit each time as the current item in the list.
2. Comprehending lists
In contrast to the for loop, list comprehension enables us to traverse through a list in a single line. This approach is thought to be one of the most reliable ways to iterate through Python lists because of how straightforward it is. For further information, see this page on LISTS AND LIST COMPREHENSION IN PYTHON. Let's look at an illustration for now:
Code:
fruits_list = [ "Mango", "Apple","Peach", "Banana", "Lichi", "Guava"]
[print(frt + " juice") for frt in fruits_list]
As you can see, we are utilizing what appears to be another for loop: for fruit in fruits. What makes this a list comprehension is that the print() command is surrounded by square brackets, along with the command and the for..in structure.
Output:
[Running] python -u "d:\Programming\Python\test.py"
Mango juice
Apple juice
Peach juice
Banana juice
Litchi juice
Guava juice
[Done] exited with code=0 in 0.379 seconds
As you can see, we made the list of fruits in the same way as we did in the earlier example. But this time, we added the word "juice" to the end of the list item and printed it using list comprehension.
3. A loop for a range ()
The range() function and a for loop are two additional ways to iterate through a Python list. From the starting and ending indexes supplied, range() creates a sequence of numbers. The syntax of the range function is as follows: (An index refers to the position of elements in a list; the first list item has an index of 0, the second is 1, and so on.)
Syntax:
range (start, stop, step)
Only the stop argument is necessary; the start and step parameters are not. The step controls whether or not list items are skipped; it is by default set to 1, implying that no items are did skip. The function creates a range object with all the items from 0 to stop-1 if you only give one parameter, which is the stop index.
Here is an illustration that will display the name of the fruit and its position in the list:
Code:
fruits_list = [ "Mango", "Apple","Peach", "Banana", "Lichi", "Guava"]
# builds an object with elements ranging from 0 to 5.
for j in range (len (fruits_list)):
print ("The fruit list at index", j, "contains the", fruits_list[j])
Output:
[Running] python -u "d:\Programming\Python\test.py"
The fruit list at index 0 contains the Mango
The fruit list at index 1 contains the Apple
The fruit list at index 2 contains the Peach
The fruit list at index 3 contains the Banana
The fruit list at index 4 contains the Lichi
The fruit list at index 5 contains the Guava
[Done] exited with code=0 in 0.336 seconds
An alternative strategy would be to display only some of the fruits according to their index. To accomplish this, we would use the range() method to define the for loop's beginning and ending indexes:
Code:
fruits_list = [ "Mango", "Apple","Peach", "Banana", "Lichi", "Guava"]
# Builds an object with elements ranging from 1 to 4.
for j in range(1, 5):
print(fruits_list[j])
Output:
[Running] python -u "d:\Programming\Python\test.py"
Apple
Peach
Banana
Lichi
[Done] exited with code=0 in 0.346 seconds
Remember that 0 is the initial index in Python and that 1 and 4 are the only fruits that were returned in response to our request.
4. An enumerate for loop ()
There are instances when you need to know the position of the entry in the list that you are accessing. You can use the enumerate() function to add a counter and return a "enumerate object," which is what it does. A straightforward Python for loop can be used to unpack the elements included in this object. The expense of maintaining a tally of the number of elements during a straightforward loop is therefore reduced by an enumerate object.
Here is an example:
Code:
fruits_list = [ "Mango", "Apple","Peach", "Banana", "Lichi", "Guava"]
for index, elmt in enumerate(fruits_list):
print (index, ":", elmt)
Running the code above yields the following list of elements and their indices:
Output:
[Running] python -u "d:\Programming\Python\test.py"
0 : Mango
1 : Apple
2 : Peach
3 : Banana
4 : Lichi
5 : Guava
[Done] exited with code=0 in 0.348 seconds
5. Using lambda in an A for loop
The anonymous lambda function in Python is a function that evaluates and returns the result of a mathematical expression. Lambda can therefore be used as a functional object. Let's practice using lambda while iterating through a list.
A for loop will be created to run through a list of integers, locate every number's square, and save or add it to the list. We'll print a list of squares to finish. Here is the key:
Code:
list_1 = [2, 4, 6, 8, 10, 12, 14, 16]
list_2 = []
# Square number using the lambda function
tmp = lambda j:j**2
for j in list_1:
# Add to list_2
list_2.append (tmp(j))
print (list_2)
Output:
[Running] python -u "d:\Programming\Python\test.py"
[4, 16, 36, 64, 100, 144, 196, 256]
[Done] exited with code=0 in 0.356 seconds
We go through the list and determine the square of each integer using lambda. A for loop is utilized to loop through lst1. The add() function passes each integer in a single loop, saving each one to list_2.
The map() method can be used to further improve the efficiency of this code:
Code:
list_1 = [2, 4, 6, 8, 10, 12, 14, 16]
list_1 = list (map (lambda a: a ** 2, list_1))
print (list_1)
Output:
[Running] python -u "d:\Programming\Python\test.py"
[4, 16, 36, 64, 100, 144, 196, 256]
[Done] exited with code=0 in 0.334 seconds
A map object (that is an iterator) is created by the results of applying the provided method to each item in the specified iterable using the map() function.
These two codes get the exact same result:
6. A while Loop
A while loop can also be used to iterate through a Python list. One of the initial loops that new programmers encounter is this one. It's also among the simplest to understand. If you think about the loop's name, you'll quickly see that the word "while" refers to the time period or an interval. A piece of code that is performed repeatedly is referred to as a "loop." So, a while loop runs up until a predetermined condition is satisfied.
The size of the list is the condition in the code below; the I counter is first set to zero and then increments by 1 each time the loop displays an item from the list. The while loop ends when I exceed the total number of entries in the list. Examine the code:
Code:
fruits_list = [ "Mango", "Apple", "Peach", "Banana", "Lichi", "Guava"]
k = 0
while k < len (fruits_list):
print (fruits_list[k])
k = k + 1
Output:
[Running] python -u "d:\Programming\Python\test.py"
Mango
Apple
Peach
Banana
Lichi
Guava
[Done] exited with code=0 in 0.323 seconds
It's crucial to keep in mind that the code above's k = k + 1 can alternatively be written as k += 1.
Our method guarantees that after a specific number of iterations, the condition k <len(fruits) will be satisfied. It's crucial to appropriately terminate while loops.
7. The NumPy Library
The techniques we've discussed thus far all made use of brief lists. However, when working with larger amounts of data, efficiency is crucial. Let's say you have a vast collection of single-dimensional, one-dimensional lists. The ideal method to loop through large lists in this situation is to use an external library, such as NumPy.
By improving the efficiency of iteration, NumPy lowers the overhead. The lists are transformed into NumPy ARRAYS to do this. The for loop can be utilized to iterate across these arrays just like it can with lists.
It's crucial to remember that the method we describe here is only applicable to arrays of single data types.
Code:
import numpy as np
num = np.array( [2, 4, 6, 8, 10, 12, 14, 16])
for n in num:
print(n)
Output:
2
4
6
8
10
12
14
16
[Done] exited with code=0 in 2.555 seconds
Although for n in num: was used in this example for simplicity's sake, it is typically preferable to utilize for n in np.nditer(num): when working with huge lists. In comparison to using a straightforward for loop, the iterator that the np.nditer method returns can navigate the NumPy array.
Conclusion:
Python loops are practical because they let you run a section of code repeatedly. You'll regularly encounter situations where you must repeatedly carry out the same activities; loops make this task easier for you to do.
You now understand a variety of Python looping techniques.