Now let's look at how to search for values in a sequence. Let's create a list with some data:
data = [3.5, 1.2, 4.0, 8.1, 0.4]
The in
operator can be used to check if a given value is contained in a list. It returns True
if the value is contained in the list and False
otherwise. For instance:
print(3 in data)
would output False
because the number 3 is not contained in the list data
. Conversely
print(0.4 in data)
would output False because the number 0.4 is contained in the list.
To identify where a particular element is in a list, we can use the index
method on list, which works as follows:
print(data.index(0.4))
This outputs 4, because that is the index of the element 0.4 in the list data
.
NOTE: If you try to use the index
method to retrieve the index of a value that is not contained in the list, Python will raise an exception (more on exceptions at a later stage).
Create a list containing the values 4, 3, 2, 1 and 0, in this order, and assign it to a variable called data
.
Then, use the index
method to retrieve the index of the value 1 and assign it to the variable one_index
.