×

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.


Related Topics

How to Iterate a List in Python

As we know, a List is one of the four unique data structures available in Python; in this article, we will deep dive into understanding iterating through a list and...

3 minutes read.

Django vs NodeJS

Django and NodeJS are open-source frameworks used to develop web applications. Both Django and NodeJS are cross-platform and robust technology used for developing versatile web applications and mobile applications. Django Django is...

2 minutes read.

Python Program to Print Sum of all Elements in an Array

Python program to print sum of all elements in an array A set of objects stored in contiguous memory locations is referred to as an array. The concept is to keep...

2 minutes read.

How to build an Auto Clicker using Python?

What is an Auto Clicker? An Auto Clicker is software that is used for automating the click of a mouse on any particular element on the computer screen and controlling the...

8 minutes read.

Flutter with tensor flow in python

Python : Python is an object oriented programming language which is highly interpreted and is highly interactive. Python was created by Guido van Rossum in the year 1985 – 1990 .The...

3 minutes read.

Data Distribution in python

Before discussing data distribution, we will discuss each word that is data and Distribution. What is meant by data? A collection of raw facts and figures is called data. The word "raw"...

18 minutes read.

Python Errors and exceptions

Exceptions and errors are the obstacles a programmer constantly faces while writing a program. Firstly, we need to understand what are errors and exceptions and the difference between these two...

6 minutes read.

Python Ways to find nth occurrence of substring in a string

Introduction In Python, a string is a collection of characters that can be employed to conduct additional operations. In Python, a substring is a group of characters that are a part...

4 minutes read.

Python Support

Python Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

3 minutes read.

Python bool()

Python bool() class The bool() class in Python returns the boolean value for the specified object. Syntax class bool([x]) Parameter object: This parameter represents the object, like String, List, Number etc. Return It will always return True, except...

1 minute read.

Python Combination

Python Combination Permutations and combinations are the important part of our mathematical tools. We use them often in our Python programs. In this tutorial, we will learn about combinations in Python...

6 minutes read.

Installing Packages in Python

It's critical to understand that the term "package" here refers to a collection of software that must be installed (i.e. as a synonym for a distribution). It has nothing to...

6 minutes read.

Front end in python

Python : Python is an object oriented programming language which is highly interpreted and is highly interactive. Python was created by Guido van Rossum in the year 1985 – 1990 .The...

4 minutes read.

Sort a dataframe based on a column in Python

Sorting the dataframe based on a column requires pandas which is An open-source library called Python Pandas is described as offering high-performance data processing in Python. For both professionals and...

4 minutes read.

How to comment out a block of code in Python

When you are writing code in Python, you may want to document it. You need to mention why a piece of code functions, for instance. Mathematics, algorithms, and intricate business...

4 minutes read.

Python Linked List

Linked List Linked lists non-contiguous linear data structure which is made up of nodes and used to store value and a pointer pointing to the next node. It is linked with...

6 minutes read.

Python MySQL

In this article, we are going to learn the following: How to connect Python to MySQL.How to create a new Database.Procedure for connecting the newly created database.Procedure for connecting the already...

7 minutes read.

Python String index() method

Python String index() method The string.index() method in Python finds the lower index of the first occurrence of the specified value or raise a ValueError if the substring is not found. Syntax index(sub[, start[, end]]) Parameter sub:...

2 minutes read.

Python frozenset()

Python frozenset() class The frozenset() class in Python returns a new frozenset object, optionally with elements taken from iterable. Syntax class frozenset([iterable]) Parameter iterable: This parameter represents an iterable object, like list, set, tuple etc. Return This class returns an unchangeable...

1 minute read.

Python Argmin

Introduction The argmin function is defined as numpy.argmin(). This function returns the index of the minimum value or element from a Numpy array in a specific axis. An array is taken...

3 minutes read.