So far, we have seen how to store a sequence of values and how to retrieve them using indexing, slicing and searching.
Now we will start looking at performing some calculations on sequences. Python provides a few functions out of the box. Assuming data
is a list or tuple:
sum(data)
sums all the values in datamin(data)
and max(data)
return the minimum and maximum value in the sequence data.len(data)
returns the number of elements in the sequence (i.e. the length)You can also perform operations on lists which return new lists. For instance, you can concatenate two lists using the +
operator
a = [1, 2] b = [3, 4] print(a + b)
which would print [1, 2, 3, 4]
. Similarly, you can use the *
operator to concatenate a list with itself a given number of times
a = [1, 2] print(a * 3)
which would print [1, 2, 1, 2]
.
Create a list called data
containing 5 numeric values of your choice.
Using the functions above, calculate the average of the values stored in data
and assign it to a variable called average
.