Let's say we define a list containing the number of data points we collected:
data = [1.2, 3.8, 0.2, 0.9, 5.9]
Now, let's say we would like to retrieve the value of a given data point. To do that, you use indexing.
To index on a list, you can use the variable name, followed by square brackets containing the index of the element you want to retrieve, for instance:
first_value = data[0] second_value = data[1]
One thing to note is that indexing in Python is zero-based. This means that the first element in a sequence corresponds to index 0, the second element corresponds to index 1, and so on.
To access the last value, you can use negative indices, for instance:
last_value = data[-1] second_to_last_value = data[-2]
Slicing in tuples works in the same way, i.e. you still use square brackets. For instance:
data = (1.2, 3.8, 0.2, 0.9, 5.9) first_value = data[0]
Define a list containing 5 values (you can pick whatever values you want) and assign it to a variable called data
. Then, use indexing the retrieve the first, fifth and second to last values and assign them to the following variables, respectively:
first
fifth
second_to_last