A List in Python is used to store a collection of values. Let’s try to understand some methods to use a List in Python easily and effectively.

What is a List?

A List in Python is a collection of values. The values can be of the same data type or different data types. A new List can be created by enclosing a collection of values within a square bracket. Once created the values in the list can be modified, new values can be added and existing values can be deleted. Let’s write some code to understand the list in a better way.

#creating a List in Python
numbers = [10, 20, 30, 40]              #a list is created like this
print("The list is ", numbers)          #display all the elements
print("The length is ", len(numbers))   #the length of the list
print("The type is ", type(numbers))    #the type of the list

In the above code, the length of the list can be found by using the len() function. The type() function displays the data type as <class ‘list’>

How to iterate through the List?

Iterating through a list is the process of accessing each element of the list in the order in which the elements are stored. A for loop or even the while loop can be used to iterate over the list.

Iterating using a for loop

The for loop can be used to iterate through the list. Let’s write some code to display each number from the list along with the square of that number.

#iterating through a list
numbers = [5, 10, 12, 20]              
for n in numbers:                       
    print(n, n*n)                       #variable n contains the list element

As visible in the above code, iterating over the list using a for loop is quite easy and convenient. However, in case you need the index value of each element, a while loop can be used instead.

Iterating using a while loop

The standard while loop can also be used to iterate through the list. Let’s write the code to display each number along with the square of that number using a while loop now.

#iterating through a list
numbers = [5, 10, 12, 20]              
count = len(numbers)                    #the length of the list
i =0 
while i<count:
    n = numbers[i]                      #accessing each element through a index
    print(n, n*n)                       #display the element and its square 
    i=i+1                               #increment the index value

In the above code, we get the count of the list elements by using len() function. Then using a while loop each element is accessed using the index value. The index value starts from 0. The first element is stored at index value 0.

Last modified: March 21, 2023

Author