What is a Python list?

A Python list is an ordered and changeable collection of data objects. Unlike an array, which can contain objects of a single type, a list can contain a mixture of objects.

A Python list of 5 objects.
A Python list of 5 objects.

As evident in the illustration above, a list can contain objects of any data type, including another list. This makes the list data structure one of the most powerful and flexible tools in Pythonic programming.

List creation

Defining a list in Python is really quite simple. The name of the list has to be specified, followed by the values it contains:

# Initiliazing a list with 5 objects
myList1 = [20, 'Edpresso', [1, 2, 3], 3.142, None]
print(myList1)
# Initializing an empty list
myList2 = []
print(myList2)

Accessing an element

A list element can be accessed using its index. The index is the position of an element in the list.

Similar to other languages, Python list elements are indexed from 0. This means that the first element will be at the 0 index.

To access an element, its index is enclosed in the [] brackets:

Accessing the fourth element in the list.
Accessing the fourth element in the list.
myIntList = [1,3,5,2,4]
print(myIntList[3]) # Accessing the 4th element

Adding and removing elements

The size of a list is not fixed. Elements can be added and removed at any point.

myList = ['a', 'b', 'c', 'd', 'e', 'f']
# Add an element at the end
myList.append('g')
print(myList)
# Insert element at a specific index
# insert(index, value)
myList.insert(3, 'z') # Insertion at the 3rd index
print(myList)
# Delete an element from the end
myList.pop()
print(myList)
# Delete the value at a specific index
del myList[1]
print(myList)
# Accessing the length of a list
print(len(myList))
Copyright ©2024 Educative, Inc. All rights reserved