Now we introduce the concept of mutability, which is the main difference between lists and tuples.
Lists are mutable, which means that their value can change after they are defined.
Tuples, on the other hand, are immutable. Once they are defined you can no longer change them.
Here is an example. The append method appends a new value to a list after it is defined.
data = [9, 2, 7, 3] data.append(5) print(data)
This would print [9, 2, 7, 3, 5]. Notice how we do not redefine the variable data. Instead, the append method modified the value that was previously assigned to the variable data.
Here are a few other examples that modify lists:
data.sort() sorts the elements in ascending orderdata.extend(more_data) extends the list data with another list more_datadata.insert(index, value) inserts the value value in the position indexdata.clear() removes all elements from the list datadata.pop() removes the last element of a list (and returns it as a result)Tuples are immutable so none of the methods in this snippet will work.
Note: Tuples are also more memory efficient than lists, so they can be sometimes preferred, especially in data intensive applications.
Create a variable called data and assign to it the values 4, 3, 1 and 2, in this order.
Using the methods above, can you transform data so that it is equal to [0, 1, 2, 3, 4, 5]?