Operators with Lists (and Tuples)
In this lesson we will apply a few of the operators we have learned to lists. The operations we will look at can also be applied to tuples.
Addition +
, multiplication *
,
and equality ==
with lists
Let's consider two lists, x
and y
.
If we apply the addition operator +
to these lists,
then we will get a new list that contains the elements of both lists
combined. Multiplication with a list, same as a string, will repeat
the list that number of times. Equality with a list will return
True
if all of the elements within the lists are the same,
and False
otherwise.
Using Numpy with lists
The above operations may have been surprising, after all, what if
we want to perform element-wise arithmetic operations on the elements
in a list? Using the basic arithmetic operators like +
directly on lists results in concatenation rather than element-wise
addition. To achieve element-wise operations, we can utilize a library
called NumPy, which provides a wide array of functions for working with
data structures such as lists.
NumPy is a library that provides
many useful functions for working with lists and other data structures.
Let's see how we can use NumPy to do element wise addition,
subtraction, multiplication, and raise to the power of.
We may access the NumPy library by importing it with the line
import numpy as np
. Note that we use something called an
alias, np
, to refer to the library. This is a common
practice when importing libraries. Then we may access any functions
within the library by prefacing it with a period.
- addition: We can use the
np.add
function to add the elements of two lists together. - subtraction: To do subtraction the
np.subtract
function can be used to subtract the elements of the second list from the first list. In this example we pass in the single value 2, where NumPy treats this as a list of 2s. - multiply: Multiplication can be done with the
np.multiply
function. - power: And we can use the
np.power
function to raise the elements of the first list to the power of the second. Again, NumPy treats the single value 2 as a list of 2s.
Practice Question
Suppose lists year01_sales
and year02_sales
are lists
containing the sales for each month of the year. Which of the following
operations will calculate the average monthly sales?
score: 0%
Let's see how operators can be used with sets in the next lesson.