×

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

Python Deep Copy and Shallow Copy

Assignment statements in Python create bindings between a target and an object, not copies of them. The = operator only makes a new variable that shares the reference to the...

3 minutes read.

os.stat() method in Python

In Python, the os module provides the capacity to interact with the operating system. The operating system comes under the Python module. In this module, Python provides a specific feature...

3 minutes read.

Composition in Python

Composition in Python Composition is one of the important concepts of Object-oriented programming (OOPs). Composition basically enables us for creating complex types objects by combining other types of objects in the...

6 minutes read.

Python List index() method

Python List index() method The list.index () method in Python returns the position at the first occurrence of the specified value. Syntax list.index(x[, start[, end]]) Parameter element – This parameter represents the element whose lowest index will be returned. start (Optional)...

2 minutes read.

Linear Regression using Sklearn with Example

This article will examine Python's global, local and non-local variables and show you how to use them to write code without problems. Let's quickly review what a variable in Python is...

8 minutes read.

Find Last Occurrence of Substring using Python

Introduction When planning to work with strings, we may need to determine whether a substring is present. This issue is rather typical, and there have been numerous discussions about how to...

3 minutes read.

Dictionary to JSON Python

In python JSON (JavascriptObject Notation). In the programming language, the text file is made using the script file.We can use many built-in packages which arenamedJSON.Before using the packages, we have...

3 minutes read.

Find Words in String Python

Python : Python programming language is considered a general purpose; it is a high-level programming language that is not much difficult but easier to learn. Python programming language is rich in...

5 minutes read.

Python zip() Function

Python zip() Function The zip() function makes an iterator that aggregates elements from each of the iterables and returns an iterator of tuples. Syntax zip(*iterables) Parameter iterables: Iterator objects that will be joined together Return This function...

1 minute read.

Python print() function

Python print() function The print() function prints the specified message to the screen or other standard output devices. Syntax print(*objects,sep=' ',end='\n',file=sys.stdout,flush=False) Parameter objects: This function represents an object, which will be converted to a string...

1 minute read.

GUI Calculator in Python

Introduction In Python, we can develop a GUI(Graphical User Interface) with multiple options. It offers us some great and commonly used methods for the development of the Graphical User Interface. Tkinter...

4 minutes read.

Python Hash Table

An Introduction to Hashing A technique which used to identify a particular object uniquely from a set of similar objects is known as Hashing. Some real-life examples of hashing implementations include: A...

9 minutes read.

Python Stack

Python Stack: The work Stack is defined as arranging a pile of objects or items on top of another. It is the same method of allocating memory in the stack...

10 minutes read.

Python String rfind() method

The string. rfind() method in Python returns the highest index in the string if the substring sub is found else it returns -1 if the substring is not found. Syntax string.rfind(sub [,start [,end]]) Parameter sub: This parameter...

2 minutes read.

Latest Project Ideas using Python 2024

Python is one of the well-known languages for programming in the contemporary domain of computer science. The demand to adopt Python for IT purposes is steadily increasing because of its...

7 minutes read.

How to upgrade PIP in python

We use the PIP command in our command prompt to install any package. PIP is used to install published Python packages in the PyPI (Python package index) or other indices....

3 minutes read.

JWT Decode Python

Python's PyJWT package makes it possible to encrypt and decrypt JSON Web Tokens (JWT). JWT is a public, recognized global benchmark for safely expressing demands between two parties (RFC 7519). JSON...

7 minutes read.

An Introduction to Subprocess in Python with Examples

Subprocess in Python By starting new processes, the Python function subprocess is utilized to run extra programs and applications. It makes it possible to run brand-new apps straight from a Programming...

6 minutes read.

Exrex Python

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...

4 minutes read.

How to make a firewall in Python?

Firewall: The firewall is a network which controls the incoming and outgoing network traffics of a monitor. It blocks the dataset based on the set of rules written in the security...

3 minutes read.