Home »
Python
Python Lists: A Complete Tutorial with Examples
Python List Tutorial: In this tutorial, we will learn about Python lists and the various operations on a list with the help of examples.
By IncludeHelp Last updated : June 15, 2023
Python List - An Introduction
Python list is one of the 4 special built-in data types other than a tuple, dictionary, and set. Python list is used to store multiple items. It is different from an array because a list can store heterogeneous types of data (different data types). Another point that differentiates a list and an array is that lists are dynamic that is there is no need to set the size of a list whereas we need to set the size of an array at the time of its declaration. A list can be created using the square brackets [].
Some of the features of Python lists are:
- List items are ordered; hence, we can select any of the list elements with the help of its index.
- The first item of the list has an index [0], the second item of the list has an index [1] and the nth item of the list (last item) has an index [n-1].
- The list is mutable that is the items on the list can be updated at any time.
- List allows duplicates.
- List allows all the basic operations like insertion, modification, and deletion.
- If we add a new element to a list, it will be added to the end of the list.
- The total number of elements/items in a list represents the length of the list. The length of the list can be accessed with the help of the len() function.
In this tutorial, you'll learn:
Create an empty list
To create an empty list, we just need to assign empty square brackets [] to a variable.
Example
# Empty List
python_list = []
print("Empty list:", python_list)
Output:
Empty list: []
Create a list with multiple elements
To create a list with multiple elements, we need to write all the elements inside the square brackets, if any element is of type string, it will come inside double quotes ("").
Example
# List
python_list = [1,2,3,"Four",True,5.0]
print("List:", python_list)
Output:
List: [1, 2, 3, 'Four', True, 5.0]
Access elements from a list
By using the list index which starts from 0, we can easily access the elements of the list. Use the index operator [] and pass an index to access specific element from the list.
Example
# Accessing list elements from
# a list in Python
# Creating a List with multiple elements
cities_list = ["New Delhi", "Mumbai", "Chennai", "Bangalore"]
# Access the elements Using
# index operator [] with index number
print("List elements are:")
print(cities_list[0])
print(cities_list[1])
print(cities_list[2])
print(cities_list[3])
Output:
List elements are:
New Delhi
Mumbai
Chennai
Bangalore
Iterate over a list
To iterate over a list, you can use simple for loop.
Example
# Creating a List with multiple elements
cities_list = ["New Delhi", "Mumbai", "Chennai", "Bangalore"]
# iterate over a list
for city in cities_list:
print(city)
Output:
New Delhi
Mumbai
Chennai
Bangalore
Type of a list
The type of a list is class 'list'. To get the type of a list, you can simply use type() method.
Example
# list
cities_list = ["New Delhi", "Mumbai", "Chennai", "Bangalore"]
# print type of a list
print("Type of list:", type(cities_list))
Output:
Type of list: <class 'list'>
Size of a list
To find the size of the given list, we use len() method. The len() method accepts the list name and returns the total number of list elements.
Example
# Getting size of a list in Python
# Creating a List with multiple elements
cities_list = ["New Delhi", "Mumbai", "Chennai", "Bangalore"]
# Printing the list
print("cities_list:", cities_list)
# Getting and printing the size of
# the list
print("Length of the cities_list is:", len(cities_list))
Output:
cities_list: ['New Delhi', 'Mumbai', 'Chennai', 'Bangalore']
Length of the cities_list is: 4
Insert elements to a list
To insert an elements into a list, we use append() method. And, to insert multiple elements in a list, we need to loop over the list n number of times where n is the number of elements we want to insert.
Example
# Inserting the elements into a list
# in Python
# Creating an empty list
cities_list = []
# Inserting two elements one-by-one
cities_list.append("New Delhi")
cities_list.append("Chennai")
# Taking input and Inserting 5 elements
for i in range(5):
cities_list.append(input("Enter city name : "))
# Printing the list
print("cities_list:", cities_list)
# Getting and printing the size of
# the list
print("Length of the cities_list is:", len(cities_list))
Output:
Enter city name : Bangalore
Enter city name : Gwalior
Enter city name : Bhopal
Enter city name : Ayodhya
Enter city name : Vrindavan
cities_list: ['New Delhi', 'Chennai', ' Bangalore ', 'Gwalior', 'Bhopal', 'Ayodhya', 'Vrindavan']
Length of the cities_list is: 7
Modify list elements
To modify any element, we need to know its location, and the location of any element is depicted by its index position.
Suppose we have a list of 5 elements; therefore, we must have indices between the range 0-4. Now, if we want to change the 3rd element of the list, we will access the 2nd index of the list to update its corresponding value.
Example
# Python list with some elements
python_list = [1,2,3,4,5]
# Printing the list
print("Original List: ",python_list)
# Inserting an elements at 2nd index
python_list[2] = "Hello"
# Printing the updated list
print("Updated List: ",python_list)
Output:
Original List: [1, 2, 3, 4, 5]
Updated List: [1, 2, 'Hello', 4, 5]
Remove list elements
To delete any element of a list, we will use the remove() method. We need to pass the element that we need to remove from the list.
Example
# Python list with some elements
python_list = ['Ram','Shyam','Seeta','Bablu','Geeta']
# Printing the list before deletion
print("List before deletion: ",python_list)
# Remove an element
python_list.remove('Bablu')
# Printing the list after deletion
print("List after deletion: ",python_list)
Output:
List before deletion: ['Ram', 'Shyam', 'Seeta', 'Bablu', 'Geeta']
List after deletion: ['Ram', 'Shyam', 'Seeta', 'Geeta']
Remove all list elements
To remove all elements from the list, we use clear() method.
Example
# declaring a list
cities = ["New Delhi", "Mumbai", "Banglore"]
# printing elements before clearing the list
print("Before clear() method...")
print("cities = ", cities)
# clearing the list
cities.clear()
# printing elements after clearing the list
print("After clear() method...")
print("cities = ", cities)
Output:
Before clear() method...
cities = ['New Delhi', 'Mumbai', 'Banglore']
After clear() method...
cities = []
List Methods
Python has a set of various built-in methods to work with the lists.
Methods |
Description |
append() |
It is used to add an element at the end of the list. |
clear() |
It is used to clear the list i.e., to remove all elements from the list. |
copy() |
It is used to get a copy of the list |
count() |
It is used to get the number of elements with the specified value from the list. |
extend() |
It is used to extend a list; it extends the list by inserting the list of the elements at the end of the current list. The method is called with this list (current list, in which we have to add the elements) and another list (or any iterable) is supplied as an argument. |
index() |
It is used to get the index of the specified element, the method is called with this list and element can be supplied as an argument, it returns the index of the first occurrence of the element in the list. |
insert() |
It is used to add an element /item at specified index to the list. |
pop() |
It is used to remove an element at the specified index/position from the list, the method is called with this list (list from which we have to remove an element) and index is supplied as an argument. |
remove() |
It is used to remove the first occurrence of the given element, the method is called with this list (the list from which we have to remove the element) and accepts the element to be removed as an argument. |
reverse() |
It is used to reverse the elements of the list, the method is called with this list (list in which we have to reverse the elements) and it reverses all elements in the list. |
sort() |
It is used to sort the list elements in the ascending and descending order, the method is called with this list (whose elements to be sorted) and accept some optional parameters (explained below under parameters), the method does not return any value, it sorts this list. |
Python Examples
List of Python list programs