Advanced Python

Unit 9, Lecture 1

Numerical Methods and Statistics


Prof. Andrew White, March 30, 2020

Becoming Pythonic

In [1]:
import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

Programming Idioms To Make Life Easier

Iterating Lists - Enumerate

In [2]:
my_list = ['hi', 'this', 'is', 'my', 'list']

for i,e in enumerate(my_list):
    print(i, e)
0 hi
1 this
2 is
3 my
4 list

Iterating Lists - Zip

In [3]:
x = range(10)
y = range(10, 20)

for xi, yi in zip(x, y):
    print(xi, yi)
0 10
1 11
2 12
3 13
4 14
5 15
6 16
7 17
8 18
9 19

List Comprehensions

This allows you to avoid a for loop when you don't want to type one out

In [5]:
powers = [xi ** 2 for xi in range(4)]
print(powers)
[0, 1, 4, 9]
In [4]:
# make y = x^2 quickly
x = [1, 3, 10]
y = [xi ** 2 for xi in x]

for xi, yi in zip(x,y):
    print(xi, yi)
1 1
3 9
10 100
In [6]:
# by convention, use _ to indicate we don't care about a variable
zeros = [0 for _ in range(4)]
print(zeros)
[0, 0, 0, 0]
In [7]:
x = [4,3, 6, 1, 4]
mean_x = sum(x) / len(x)
delta_mean = [(xi - mean_x)**2 for xi in x]
var = sum(delta_mean) / (len(x) - 1)

print(var)
3.3

Dict Comprehensions

In [8]:
x = [4, 10, 11]
y = ['number of people', 'the number 10', 'another number']

#key: value
my_dict = {yi: xi for xi, yi in zip(x,y)}

print(my_dict)
{'number of people': 4, 'the number 10': 10, 'another number': 11}

F Strings

You can simplify string formatting with f strings:

In [9]:
answer = 4
mean = -3

print(f'The answer is {answer} and the mean is {mean:.2f}')
The answer is 4 and the mean is -3.00