Lists

In this class, we will learn about lists, which are one of the most important data structures in Python.

What are lists? Link to heading

Lists are ordered collections of elements that can be any type of data. They can be used to store a variety of data, such as names, numbers, dates, etc.

How are lists created? Link to heading

Lists are created using ([]) square brackets and separating elements with commas.

Example: Link to heading

# List of names
names = ["Ana", "John", "Peter"]

#List of numbers
numbers = [1, 2, 3, 4, 5]

# Mixed list
mixed = ["Hello", 10, True]

Access list items Link to heading

Elements in a list can be accessed using their index. The index of an element is its position within the list, starting at 0.

Example Link to heading

# Print first name
print(names[0])

# Print the third number
print(numbers[2])

# Print the last element of the mixed list
print(mixed[-1])

Add items to list Link to heading

Elements can be added to the end of the list using the append() method.

Example: Link to heading

names.append("Mary")
print(names)

Delete items from the list Link to heading

Elements can be removed from the list using the remove() method or the del operator.

Example: Link to heading

# Delete the second element
names.remove("John")

# Delete the last element
of names[-1]

print(names)

Change list items Link to heading

You can change list elements using their index.

Example: Link to heading

# Change first name
names[0] = "Camila"
print(names)

Search for elements Link to heading

You can search for an element in a list using the index() method or the in operator.

Example: Link to heading

# Find the index of the first appearance of "Ana"
index = names.index("Ana")

print(index)

# Search if "Peter" is in the list
print("Pedro" in names)

Exercise Link to heading

Copy the following lists and add a new element to each with .append(), then, using the [] ​​indices, print at least 3 elements. Finally, perform a search where you print elements of the list using the search with index() or with the in operator.

names = ['Arturo', 'Laura', 'Carlos', 'Martha']
ages = [25, 36, 53, 78]
<< Variables and Data Types Basic Operators >>