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.
Creating a list
Section titled “Creating a list”Let’s make a list of fruits
# List of fruitsfruits = ['apple', 'banana', 'orange', 'pear', 'grape', 'mango']print(fruits)
Output:
['apple', 'banana', 'orange', 'pear', 'grape', 'mango']
Indexing
Section titled “Indexing”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 of fruitsfruits = ['apple', 'banana', 'orange', 'pear', 'grape', 'mango']print(fruits[1])
Output:
banana
Modifying an element
Section titled “Modifying an element”Through indexing we can modify a particular element of the list
# List of fruitsfruits = ['apple', 'banana', 'orange', 'pear', 'grape', 'mango']
# We assign a new element to the element at position 1fruits[1] = 'strawberry'print(fruits)
Output:
['apple', 'strawberry', 'orange', 'pear', 'grape', 'mango']
Adding elements
Section titled “Adding elements”To add an element to a list you must use the .append()
function
# List of fruitsfruits = ['apple', 'banana', 'orange', 'pear', 'grape', 'mango']
# New element added to the end of the listfruits.append('strawberry')print(fruits)
Output:
['apple', 'banana', 'orange', 'pear', 'grape', 'mango', 'strawberry']
Removing an element
Section titled “Removing an element”To remove an element from a list you must use the .remove()
function
# List of fruitsfruits = ['apple', 'banana', 'orange', 'pear', 'grape', 'mango']
# Remove selected elementfruits.remove('mango')print(fruits)
Output:
['apple', 'banana', 'orange', 'pear', 'grape']