×

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

What is a List in Python?

List can be defined as the ordered collection of mutable elements, which can be of any data type declared inside the [ ] separated by commas after each element. Lists are indexed, so the elements inside the List can be accessed anytime through indexing the List.

Create a List in Python

As discussed above, Lists can be declared inside the square brackets, separated by commas and can be of any data structure.

Code

Languages_List = ['Python' , 'C++' , 'Java' , 'C#']
print(Languages_List)

Output

['Python','C++','Java','C#']

Accessing Elements through Indexing from the List

 As discussed earlier, the elements we declare inside the List have indexes to access the elements, modify if necessary, and many other functions. We will now try to access the elements inside the Languages_List declared above through indexing.

See the below code for accessing the elements inside the List

Code

Languages_List = ['Python', 'C++' , 'Java' , 'C#']
print(Languages_List[1])
print(Languages_List[3])

Output

['C++']
['C#']

Now that we have seen what is a List, creating a List, and accessing the elements inside the List, we will now closely look at iterating through the Lists.

There are various methods to iterate through a List in Python, some of them being using the built-in functions in Python, iterating through the loops, namely by using a for loop or a while loop, range function, using the method of List comprehension, with the help of enumerate function.

Method-1: Using the for loop to Iterate through a List in Python

Code

List_nums = [21,33,567,986,999]
for i in List_nums:
    print(i)

Output

21
33
567
986
999

In the above code, we see that a List is declared in which it has all the numbers as its elements declared inside the square brackets separated by commas. Below the creation of the List, we have written the code to iterate through the elements inside the List using a for loop where i is the iterator. When the iterator is printed using the print function, all the elements inside the List are printed as output.

Method-2: By using the range function along with for loop

Code

List_nums = [21,33,567,986,999]
Length = len(List_nums)
for i in range(Length):
    print(List_nums[i])

Output

21
33
567
986
999

In the above code, we see that along with the variable containing list elements; we have declared another variable named length, which is calculating the length of the List that is declared, and while running the for loop over the List, we have used the range function in which the length variable which calculated the length of the List for us is passed as the argument. When the iterator is printed, we see that all the elements inside the List are printed as output.

Method-3: Using the while loop to Iterate through a List in Python

Code

List_nums = [21,33,567,986,999]
Length = len(List_nums)
i=0
while i<Length:
    print(List_nums[i])
    i+=1

Output

21
33
567
986
999

As we see, we have accessed the elements inside the List containing numbers using a while without losing the generality of the while loop syntax and with the help of another variable-Length which calculated the length of the List. Here the iterator i is declared outside the while condition and incremented after the print function is written.

Method-4: Using the List Comprehension Method in Python

Code

List_nums = [21,33,567,986,999]
[print(i) for i in List_nums]

Output

21
33
567
986
999

In the above code, we have used the concept of List Comprehension, which is familiarly known as the short method, to use the loop concept to iterate on short looping. Here the print function is passed with a parameter of i with the for loop iterating on the List, and hence we see the elements are printed.

Method-5: Using the Built-in enumerate function in Python

Code

List_nums = [21,33,567,986,999]
for i, val in enumerate(List_nums):
    print(i,",",val)

Output

0, 21
1, 33
2, 567
3, 986
4, 999

As we see, the enumerate function is passed along with the val variable, which calculates the index of the elements inside the List printed.


Related Topics

How to uninstall python

To un-install Python, we need to follow different procedures in different operating systems. In this article, we will discuss the un-installation process of Python in Windows, Mac, and Linux operating...

4 minutes read.

Python List append() Method

Python List append() Method The list.append() method in Python adds or appends an item to the end of the list. Syntax list.append(x) Parameter x: It is a required parameter that represents an element of any type (string, number,...

1 minute read.

Python Memory Management

In order to manage memory, Python uses a private heap that contains all of its data structures and objects. The Python memory manager is responsible for the internal management of...

11 minutes read.

Features of Python

Python is a powerful, easy to learn, popular programming language. It has effective data structures and its elegant syntax makes it user-friendly language. Below are the key features of Python: 1. Python...

4 minutes read.

Reason for Python So Popular

One of the languages that is witnessing outstanding development and acceptance every year in Python. Python has emerged as the programming language with the greatest rate of growth, and Stack...

3 minutes read.

How to add 2 lists in Python?

In Python, a list is defined as a data structure that contains a sequence of elements. It can contain any kind of data type inside it but in order to concatenate two...

3 minutes read.

How to Install Python

Python Installation Guide Step by Step Installing Python is quite simple and easy. In this tutorial, we will show stepwise procedure to install Python and set up the Python environment in different...

2 minutes read.

Python Escape Characters

In this tutorial, we will learn how to use the Escape Characters in Python. Escape Character: Escape Characters are used for some special meaning in our statements. It is denoted or represented...

3 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 TypeError

What is TypeError in python? TypeError is one of the exceptions in the python programming language. This exception occurs when an operation is performed on an unsupported object type or can...

6 minutes read.

Python Unit Test Cheat String

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.

Import py file in Python

In Python programming language, a module is a single layer of block of Python code that can be loaded and used by importing into other Python block of code. A module...

4 minutes read.

Python Tuple index() Method

Python Tuple index() Method The tuple.index() method of Python finds the first occurrence of the specified value and returns its index if the value is found else raises an exception if...

1 minute read.

Exit program in python

Exit program in python The quit(), exit(), and sys.exit() functions have almost the same functionality as they raise the SystemExit exception by which the Python interpreter exit and no stack traceback...

2 minutes read.

Python Program to check whether a given number is Armstrong or not

Program to check whether a given number is Armstrong or not A number is said to be an Armstrong if the sum of each digit's cube of a given number equals...

1 minute read.

Python vs Java

There are a lot of programming languages out there, and every day, a new programming language is developing in some parts of the world. Each programming language is a mixture...

5 minutes read.

Python Keywords

If you are trying to learn a programming language, you need to have a basic idea of "What are keywords" and "How they are used". You can learn about keywords in...

7 minutes read.

Python Random shuffle( ) method

The shuffle() is used to change the positions of the elements in the mutable sequences. The shuffle( ) function will change the positions of the elements in the sequence of...

3 minutes read.

Python Read Excel file

Python Read Excel file Excel is the spreadsheet application for Window, which is developed by Microsoft. The Excel stores data in the tabular form. It provides easy access to analyze and maintain the...

3 minutes read.