a shot of dev knowledge

Related tags

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.

svg viewer
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]

# Initializing an empty list
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:

svg viewer
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

# Insert element at a specific index
# insert(index, value)
myList.insert(3, 'z') # Insertion at the 3rd index

# Delete an element from the end

# Delete the value at a specific index
del myList[1]

# Accessing the length of a list

Related tags

View all Courses
Related Courses
Related Courses
View all Courses

Keep Exploring