Lists#
Python lists are very similar to C++ std::vector. They serve
the same purpose.
In particular:
We can loop over elements of a list using a
forloop, very similar to the range-based loop we saw with C++.We use
.append()in python the way we used.push_backin C++We use
[]and 0-based indexing to get an element of a list—just like in C++If we use a negative index, then we access elements from the end, e.g.,
alist[-1]is the last element in a listalist. This is similar to the C++.back()function.
We can use the
len()function to get the number of elements in a list. Unlike C++.size(), this is not a member of the list class, so we would dolen(alist).
a_list = []
a_list.append(1.0)
a_list.append(2.0)
for e in a_list:
print(e)
In python we don’t need to specify the datatype.
std::vector<double> vec;
vec.push_back(1.0);
vec.push_back(2.0);
for (auto e : vec) {
std::cout << e << std::endl;
}
In C++, when we create a vector, we need to specify what type of data it carries.
Note
Technically, python lists can hold a mix of different types, e.g., you can do:
a_list = [1, 2.5, "string"]
but this is rarely used in practice. Usually we use them with a single
type, much like with std::vector.
Checking for membership#
We can use the in operator to check if an item is in a list, for example:
names = ["Homer", "Marge", "Lisa", "Bart", "Maggie"]
"Homer" in names
List concatenation#
We can concatenate two lists using the + operator:
x = ["a", "b"]
y = ["c", "d"]
z = x + y
Example#
Small-angle approximation#
Let’s revisit our Small-angle approximation example, and rewrite it in python.
import math
angles_deg = [5.0, 10.0, 20.0, 40.0]
print(f"{'angle (d)':10} : {'angle (r)':10} {'sine':10} {'err':10}")
for a in angles_deg:
angle_rad = math.radians(a)
sine = math.sin(angle_rad)
err = abs(sine - angle_rad)
print(f"{a:10.2f} : {angle_rad:10.3f} {sine:10.5f} {err:10.5g}")
Notice:
The format strings in the
printstatements are identical to the ones in the C++ code, except now we use an f-string.We don’t need to put the loop conditions in
( ), in fact in python, it is discouraged.In python, we can use
math.radians()to convert from degrees to radians. The C++ standard library does not have a comparable function.
Average and standard deviation#
Let’s revisit our Homework #4 problem on finding the average and standard deviation of a vector, now in python.
import math
values = [1.0, 2.2, 10.5, 21.3, 25.4, 6.6, 4.2]
vsum = 0.0
for e in values:
vsum += e
vavg = vsum / len(values)
vsigma = 0.0
for e in values:
vsigma += (e - vavg)**2
vsigma = math.sqrt(vsigma / len(values))
print(f"average = {vavg:.3f}, sigma = {vsigma:.3f}")
Important
Writing explicit loops over the elements of a list is inefficient
in python, because each iteration interacts with the interpreter.
There are more efficient ways we can do this. For example,
we can use the built-in sum function:
vsum = sum(values)
and we can use list comprehensions as well, e.g.,
vsigma = sum((e - vavg)**2 for e in values)
Tip
When we cover the NumPy library later, we’ll see that there are even easier ways to do this.