Predict the output of cells 4, 8, and 12.

Watch Brandon Rhodes' presentation Names, Objects, and Plummeting From The Cliff.


In [1]:
a = [i*i for i in range(3)]
a


Out[1]:
[0, 1, 4]

In [2]:
b = a

In [3]:
b[1] = 'hello'
b


Out[3]:
[0, 'hello', 4]

In [4]:
a


Out[4]:
[0, 'hello', 4]

In [5]:
a = [i*i for i in range(3)]
a


Out[5]:
[0, 1, 4]

In [6]:
b = a[:]

In [7]:
b[1] = 'hello'
b


Out[7]:
[0, 'hello', 4]

In [8]:
a


Out[8]:
[0, 1, 4]

In [9]:
a = [i*i for i in range(3)]
a


Out[9]:
[0, 1, 4]

In [10]:
b = a.copy()

In [11]:
b[1] = 'hello'
b


Out[11]:
[0, 'hello', 4]

In [12]:
a


Out[12]:
[0, 1, 4]

Show what map() does.


In [13]:
def foo(s):
    return s + ' on the Beach.'

list(map(foo, ('sand', 'clams', 'dunes')))


Out[13]:
['sand on the Beach.', 'clams on the Beach.', 'dunes on the Beach.']

In [14]:
a = (1, 2, 3)
b = (2, 3, 4, 5)

from itertools import zip_longest

sum(map(sum, zip_longest(a, b, fillvalue=0)))


Out[14]:
20

In [15]:
sum((sum(a), sum(b)))


Out[15]:
20

In [16]:
sum(a + b)


Out[16]:
20

fstrings can handle expressions, not just variable names.


In [17]:
f'hello {sum(map(sum, zip_longest(a, b, fillvalue=0)))} world'


Out[17]:
'hello 20 world'