Skip to content

Lists

In Python, a list is a flexible data structure that allows you to store an ordered collection of elements of any type. They are mutable, which means they can be modified after creation. They are defined with square brackets [] and their elements are separated by commas.

Let’s make a list of fruits

list.py
# List of fruits
fruits = ['apple', 'banana', 'orange', 'pear', 'grape', 'mango']
print(fruits)

Output:

terminal
['apple', 'banana', 'orange', 'pear', 'grape', 'mango']

Suppose we only want a particular element from the fruits list. With this in mind, you should know that each element in a list has an index with which we can locate each element of a list, and for this we must carry out the concept of Indexing as follows

list.py
# List of fruits
fruits = ['apple', 'banana', 'orange', 'pear', 'grape', 'mango']
print(fruits[1])

Output:

terminal
banana

Through indexing we can modify a particular element of the list

list.py
# List of fruits
fruits = ['apple', 'banana', 'orange', 'pear', 'grape', 'mango']
# We assign a new element to the element at position 1
fruits[1] = 'strawberry'
print(fruits)

Output:

terminal
['apple', 'strawberry', 'orange', 'pear', 'grape', 'mango']

To add an element to a list you must use the .append() function

list.py
# List of fruits
fruits = ['apple', 'banana', 'orange', 'pear', 'grape', 'mango']
# New element added to the end of the list
fruits.append('strawberry')
print(fruits)

Output:

terminal
['apple', 'banana', 'orange', 'pear', 'grape', 'mango', 'strawberry']

To remove an element from a list you must use the .remove() function

list.py
# List of fruits
fruits = ['apple', 'banana', 'orange', 'pear', 'grape', 'mango']
# Remove selected element
fruits.remove('mango')
print(fruits)

Output:

terminal
['apple', 'banana', 'orange', 'pear', 'grape']