×

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

Python Examples

In this tutorial, we will see some examples related to python. This will include some basic example questions and their code in Python. Write a program to print “Hello Python”. print(‘Hello Python’) Output Hello...

5 minutes read.

*Args and **Kwargs in Python

Let’s know about ** (dual star / asterisk) and * (star / asterisk) are operators in Python. These stars are used in Python for parameters. Args and kwargs are special...

3 minutes read.

Read Text files in Python

In Python, there are many ways to read text files. Before going into the detailed structure of reading a text file, let us understand how reading text files takes place...

4 minutes read.

Python for loop

 Python for loop A for loop in Python executes a block of code for a specified number of times, based on a given sequence. The for loop in Python is different than any other...

3 minutes read.

Read numpy array in Python

Numpy is a numerical python that deals with multidimensional arrays mostly used in storing multiple values. Python's core scientific computing package is called NumPy. This Python library provides multidimensional array...

9 minutes read.

Programs for Printing Pyramid Patterns in Python

<!-- wp:paragraph --><p>Python supports printing patterns using basic for loops. The number of rows is handled by the first outer loop, while the number of columns is handled by the...

9 minutes read.

Class and Static Methods in Python

The method is an important concept to learn for every programmer or data analyst. We know that in OOP's concept, each object has its attributes and behaviors defined through methods....

3 minutes read.

Read JSON File in Python

JSON refers to the JavaScript Object Notation. It is a Data format used for representing structured data and it is used to transfer and store data. In JSON format, the...

5 minutes read.

OSError in Python

Python: Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It is said...

4 minutes read.

Python vars() Function

Python vars() Function The vars() function in Python returns the __dict__ attribute for a module, class, instance, or any other object with a __dict__ attribute. Syntax vars([object]) Parameter object: This parameter represents any object with a __dict__attribute Return This function returns...

1 minute read.

Python String Methods

Python String Methods Python has a set of built-in string methods. The Python string methods are as follows: capitalize() The string.capitalize() method returns a copy of the string by converting the...

5 minutes read.

Python SciPy Library

Introduction SciPy, a logical library for Python is an open-source, BSD-authorized library for arithmetic, science, and design. The SciPy library relies upon NumPy, which gives advantageous and quick N-dimensional exhibit control....

6 minutes read.

Check Palindrome in Python

Python is an object-oriented high-level programming language. Python has dynamic semantics and has high-level built-in data structures which support dynamic typing and dynamic binding. Python provides rapid development. It has...

4 minutes read.

Collections in python

In this tutorial, we will see what is collection in python.  Further, we will see in-depth the different kinds of collections in python. Collections Collections in python are the built-in module used...

9 minutes read.

How to create a list in Python?

How to create a list in python Python is known for its versatility and its data structures help us to perform different kinds of operations on various datasets irrespective of their...

4 minutes 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 Euclidean Distance

Euclidean distance is the distance between two points with whatever of dimensions. We are using NumPy library to find and calculate the Euclidean distance. The NumPy library is used for...

1 minute read.

Iterators in Python

Introduction In Python, an iterator is defined as an object that enables traversing through all the values of a collection. It contains the countable number of values. The iterator is utilized to...

4 minutes read.

Python e-book free download

Python is a booming language these days. It has many applications for making code easier; it is also an open-source language. There are many sources to learn python. In this...

3 minutes read.

Standard Scalar in Python

Python is a vast and open-source language that contains many libraries, modules, and functions. These functions in python are reusable codes where we don’t need to type the whole code...

4 minutes read.