Python Lists

In this Python tutorial, we’ll learn about Python lists, creation of the list, adding or removing the elements from the list with suitable examples.

Introduction of Python list

Python gives a range of composite datatypes often referred to as sequences. The list is one of the most frequently used and versatile datatype used in Python.

Creation of list

In Python, a list is created by storing all the elements inside a square bracket [ ], separated by commas.
It can have any number of items and they may be of different types such as integer, float, string, etc.

Example code to create a list

# empty list
my_list = []
# list of integers
my_list = [1, 2, 3]
# list with mixed data types
my_list = [1, "Hello", 3.4]

Accessing elements from the list

The index operator [] is used to access an item in a list. Index starts from 0. So, a list having 5 elements will have an index from 0 to 4.
Trying to access other elements, not in the index will raise an IndexError. The index must be an integer. The usage of float or other types will result in TypeError.

Example code to access an element from the list

my_list = ['p','r','o','b','e']
# Output: p
print(my_list[0])
# Output: o
print(my_list[2])
# Output: e
print(my_list[4])
# Error! The only integer can be used for indexing
# my_list[4.0]
# Nested List
n_list = ["Happy", [2,0,1,5]]
# Nested indexing
# Output: a
print(n_list[0][1]) 
# Output: 5
print(n_list[1][3])

Deleting or removing elements from the list

The deletion of one or more elements from a list can be done using the keyword del. It can even delete the entire list.

Example code to delete a list

my_list = ['p','r','o','b','l','e','m']
# delete one item
del my_list[2]
# Output: ['p', 'r', 'b', 'l', 'e', 'm'] 
print(my_list)
# delete multiple items
del my_list[1:5] 
# Output: ['p', 'm']
print(my_list)
# delete entire list
del my_list 
# Error: List not defined
print(my_list)

Leave a Comment

Your email address will not be published. Required fields are marked *