Level 1
0 / 100 XP

Python Lists

In Python, a list is a data structure that stores an ordered collection of items. Lists are very flexible and they can store items of any data type, including other lists. In Python, you can access and modify the items in a list using indexing and slicing.

Creating a List

To create a list in Python, use square brackets [] and separate the items in the list with commas. Here are some examples of creating lists in Python:

Text
# Create an empty list my_list = [] # Create a list of numbers numbers = [1, 2, 3, 4, 5] # Create a list of strings colors = ["red", "green", "blue"] # Create a list of mixed data types mixed = [1, "two", 3.0, [4, 5]]

As you can see, a list can store items of any data type, including other lists.

Accessing and Modifying List Items

In Python, you can access the items in a list using indexing. To access an item in a list, use the square bracket notation [] and specify the index of the item you want to access. In Python, the index of the first item in a list is 0, and the index of the last item in a list is -1. Here are some examples of accessing items in a list:

Python
# Access the first item in a list print(numbers[0]) # Output: 1 # Access the last item in a list print(numbers[-1]) # Output: 5 # Access a range of items in a list print(numbers[1:3]) # Output: [2, 3]

list, use the square bracket notation [] and specify the index of the item you want to modify. Then, use the assignment operator = to assign a new value to that item. Here are some examples of modifying items in a list:

Python
# Modify an item in a list numbers[0] = 10 print(numbers) # Output: [10, 2, 3, 4, 5] # Add an item to the end of a list numbers.append(6) print(numbers) # Output: [10, 2, 3, 4, 5, 6] # Remove an item from a list…