A list in Python is an ordered and mutable collection of elements (Mutable means the elements of a list can be modified after the list’s creation).
Lists are one of the most versatile and widely used data structures. They allow us to store ordered collections of elements, such as numbers, strings, or other objects.
Characteristics of Lists:
- Mutability: The elements of a list can be modified after the list’s creation
- Ordered: The elements of a list are ordered and maintain the order in which they were added
- Can contain any data type: A list can contain elements of different data types, such as integers, strings, floats, or other lists
If you want to learn more, check out the Introduction to Programming Course
Creating a list
Lists are defined using square brackets [] and elements are separated by commas.
In this example, my_list is a list containing the numbers from 1 to 5.
my_list = [1, 2, 3, 4, 5]
It’s also possible to create empty lists, and later add elements as needed.
empty_list = []
Common operations with lists
Nested lists
In Python, it’s possible to have lists inside lists (this is known as nested lists or multidimensional lists).
For example like this,
nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(nested_list[0][1]) # Result: 2
