You can use them to store all sorts of things from numbers and strings to tuples and even more lists!
But before we dive into how to create, modify, and manipulate lists, something that might surprise you: mutability.
In Python (and many other programming languages), a list is a mutable data type which means it can be changed after being created. This is different from an immutable data type like a string, where the value cannot be modified once it’s been assigned.
So let’s see what this looks like in action! Here’s some code that creates a list of numbers:
# Creating a list of numbers
my_list = [1, 2, 3] # Assigning a list of numbers to the variable "my_list"
# Printing the list
print(my_list) # Output: [1, 2, 3]
Now let’s modify the value at index `1`, which is currently `2`. We can do this using list slicing and assignment. Here’s what that looks like:
# Here is the context before the script:
# Now let's modify the value at index `1`, which is currently `2`. We can do this using list slicing and assignment. Here's what that looks like:
# Here is the script:
my_list = [1, 2, 3] # Creates a list with values 1, 2, and 3
my_list[1] = 42 # Replaces the value at index 1 with 42
print(my_list) # Output: [1, 42, 3] - Prints the updated list with the new value at index 1
# The script modifies the value at index 1 in the list by using list slicing and assignment. The new value, 42, is then printed out to show the updated list.
Notice how the value at index `1` has been changed from `2` to `42`. This is because lists are mutable!
But what if we want to create a new list with some of the values from our original list? We can do this using slicing and assignment, just like before:
# Creating a new list by slicing and assigning values from an original list
# Define a list with values 1, 2, 3
my_list = [1, 2, 3]
# Print the original list
print(my_list) # Output: [1, 2, 3]
# Notice how the value at index 1 has been changed from 2 to 42
# This is because lists are mutable, meaning they can be changed after creation
my_list[1] = 42
# Print the updated list
print(my_list) # Output: [1, 42, 3]
# We can create a new list by slicing and assigning values from the original list
# The syntax for slicing is [start_index:end_index], where the end_index is not included in the slice
# In this case, we are slicing from index 0 to index 3 (not including index 3)
# This will create a new list with the values 1, 42, 3
new_list = my_list[0:3]
# Print the new list
print(new_list) # Output: [1, 42, 3]
Notice how the new list `new_list` contains only the first three values from our original list. This is because slicing creates a new object in memory it doesn’t modify the original list!
It might seem like a small detail, but understanding how data types behave can save you time and headaches down the road.