In [1]:
students = ['Alice', 'Bob', 'Claudia']
grades = [5, 3, 4]
Alice 5
Bob 3
Claudia 4
In [2]:
for student, grade in zip(students, grades):
    print(student, grade)
Alice 5
Bob 3
Claudia 4
In [3]:
list(zip(students, grades))
Out[3]:
[('Alice', 5), ('Bob', 3), ('Claudia', 4)]
In [ ]:
s = """hello
world
"""
# multiline string
In [8]:
def elementwise_sum(u, v):
    """
    u, v - two lists of numbers
    returns list w
    w[i] = u[i] + v[i] for all i
    """
#    assert isinstance(u, list) and isinstance(v, list)
    return [u_ + v_ for u_, v_ in zip(u, v)]
In [9]:
assert elementwise_sum([1, 2], [3, 4]) == [4, 6]
In [10]:
elementwise_sum([1, 2], [3, 4])
Out[10]:
[4, 6]
In [11]:
elementwise_sum("Hello", "World")
Out[11]:
['HW', 'eo', 'lr', 'll', 'od']
In [14]:
gradebook = {'Alice': 5, 'Bob': 3, 'Claudia': 5}
In [15]:
type(gradebook)
Out[15]:
dict
In [16]:
gradebook['Bob']
Out[16]:
3
In [17]:
gradebook['Claudia']
Out[17]:
5
In [18]:
gradebook['Bob'] = 4
In [19]:
gradebook
Out[19]:
{'Alice': 5, 'Bob': 4, 'Claudia': 5}
In [20]:
gradebook['Daniel']
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-20-4304a21bd337> in <module>()
----> 1 gradebook['Daniel']

KeyError: 'Daniel'
In [21]:
'Daniel' in gradebook
Out[21]:
False
In [22]:
'Alice' in gradebook
Out[22]:
True
In [23]:
gradebook.get('Alice')
Out[23]:
5
In [25]:
gradebook.get('Daniel') is None
Out[25]:
True
In [28]:
gradebook.get('Daniel', 0)
Out[28]:
0
In [29]:
gradebook.get('Alice', 0)
Out[29]:
5
In [30]:
gradebook
Out[30]:
{'Alice': 5, 'Bob': 4, 'Claudia': 5}
In [31]:
for student in gradebook:
    print(student)
Alice
Bob
Claudia
In [32]:
for student in gradebook:
    print(student, gradebook[student])
Alice 5
Bob 4
Claudia 5
In [33]:
for student, grade in gradebook.items():
    print(student, grade)
Alice 5
Bob 4
Claudia 5
In [34]:
gradebook.items()
Out[34]:
dict_items([('Alice', 5), ('Bob', 4), ('Claudia', 5)])
In [35]:
sum(gradebook.values()) / len(gradebook)
Out[35]:
4.666666666666667
In [36]:
gradebook.values()
Out[36]:
dict_values([5, 4, 5])
In [37]:
gradebook.keys()
Out[37]:
dict_keys(['Alice', 'Bob', 'Claudia'])
In [38]:
gradebook = {'Alice': [3, 4], 'Bob': [5], 'Claudia': [2, 4, 1]}
In [39]:
gradebook = [{'Alice': 4, 'Bob': 5},
             {'Alice': 5, 'Claudia': 4}]
In [42]:
x = ['q']
x.append(x)
In [43]:
x
Out[43]:
['q', [...]]
In [44]:
x[1]
Out[44]:
['q', [...]]
In [45]:
x[1][1]
Out[45]:
['q', [...]]
In [47]:
sum([None, 4, 3])
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-47-b9dbf7fee52a> in <module>()
----> 1 sum([None, 4, 3])

TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'
In [48]:
my_dict = {'a': 5, 'b': 3}
In [50]:
dict.fromkeys(['1', '2', '3'], 987)
Out[50]:
{'1': 987, '2': 987, '3': 987}
In [51]:
sums = {[2, 3]: 5, [1, 2]: 3}
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-51-400a52570e1e> in <module>()
----> 1 sums = {[2, 3]: 5, [1, 2]: 3}

TypeError: unhashable type: 'list'
In [52]:
sums = {(2, 3): 5, (1, 2): 3}
In [53]:
sums[(2, 3)]
Out[53]:
5
In [54]:
squares = {2: 4, 5: 25}
In [55]:
squares[2]
Out[55]:
4
In [56]:
squares[0]
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-56-58a7a2576c1f> in <module>()
----> 1 squares[0]

KeyError: 0
In [60]:
# gradebook = {'Alice': 4, 'Bob': 5, 'Claudia': 4, 'Elizabeth': 2}
# get list of students with grade > 2
def good_students(gradebook):
    gs = []
    for student, grade in gradebook.items():
        if grade > 2:
            gs.append(student)
    return gs
In [63]:
# gradebook = {'Alice': 4, 'Bob': 5, 'Claudia': 4, 'Elizabeth': 2}
# get list of students with grade > 2
def good_students(gradebook):
    return [student for student, grade in gradebook.items() 
            if grade > 2]
In [64]:
assert good_students({'Alice': 4, 
                      'Bob': 5, 
                      'Claudia': 4, 
                      'Elizabeth': 2}) == ['Alice', 'Bob',
                                           'Claudia']
In [66]:
[x ** 2 for x in range(100) if x % 4 == 0]
Out[66]:
[0,
 16,
 64,
 144,
 256,
 400,
 576,
 784,
 1024,
 1296,
 1600,
 1936,
 2304,
 2704,
 3136,
 3600,
 4096,
 4624,
 5184,
 5776,
 6400,
 7056,
 7744,
 8464,
 9216]
In [67]:
squares = {x: x ** 2 for x in range(5)}
In [68]:
squares
Out[68]:
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
In [69]:
numbers = [5, 2, 12, 3]
numbers.sort()
In [70]:
numbers
Out[70]:
[2, 3, 5, 12]
In [71]:
numbers = [5, 2, 12, 3]
numbers.sort(reverse=True)
In [72]:
numbers
Out[72]:
[12, 5, 3, 2]
In [73]:
sorted([7, 4, 2, 8])
Out[73]:
[2, 4, 7, 8]
In [74]:
numbers = [7, 4.6, 2, 8.1]
print(sorted(numbers))
print(numbers)
[2, 4.6, 7, 8.1]
[7, 4.6, 2, 8.1]
In [75]:
"Hello" < "World"
Out[75]:
True
In [76]:
"a" < "b"
Out[76]:
True
In [77]:
"ab" < "ac"
Out[77]:
True
In [79]:
"A" < "a"
Out[79]:
True
In [80]:
ord("ё")
Out[80]:
1105
In [81]:
ord("е")
Out[81]:
1077
In [83]:
sorted(["Bob", "Alice", "Alla", "Bill"])
Out[83]:
['Alice', 'Alla', 'Bill', 'Bob']
In [85]:
table = [[4, 5], 
         [6, 3], 
         [2, 5], 
         [6, 1]]
In [86]:
sorted(table)
Out[86]:
[[2, 5], [4, 5], [6, 1], [6, 3]]
In [87]:
[1, 4] < [2, 0]
Out[87]:
True
In [90]:
[1, 3] < [1, 2, 1]
Out[90]:
False
In [91]:
def subs2(f):
    return f(2)
In [92]:
def plusodin(x):
    return x + 1
In [93]:
from math import log, sqrt
In [94]:
subs2(plusodin)
Out[94]:
3
In [95]:
subs2(sqrt)
Out[95]:
1.4142135623730951
In [96]:
sorted(["hello", 'this', 'world', 'is', 'the', 'best'],
       key=len)
Out[96]:
['is', 'the', 'this', 'best', 'hello', 'world']
In [97]:
sorted(["hello", 'best', 'this', 'world', 'is', 'the'],
       key=len)
Out[97]:
['is', 'the', 'best', 'this', 'hello', 'world']
In [112]:
table = [[4, 5], 
         [6, 3], 
         [2, 5], 
         [6, 1]]
# sort by second column
def my_sort_key(item):
    print("my_sort_key invoked, item =", item)
    return item[1]
sorted(table, key=my_sort_key)
my_sort_key invoked, item = [4, 5]
my_sort_key invoked, item = [6, 3]
my_sort_key invoked, item = [2, 5]
my_sort_key invoked, item = [6, 1]
Out[112]:
[[6, 1], [6, 3], [4, 5], [2, 5]]
In [100]:
sorted(table, key=lambda z: z[1])
Out[100]:
[[6, 1], [6, 3], [4, 5], [2, 5]]
In [101]:
def foo(x):
    return x ** 2
In [102]:
foo(3)
Out[102]:
9
In [103]:
(lambda x: x ** 2)(10)
Out[103]:
100
In [104]:
sorted([4, 6])
Out[104]:
[4, 6]
In [105]:
num = [4, 6]
sorted(num)
Out[105]:
[4, 6]
In [106]:
from operator import itemgetter
In [107]:
f = itemgetter(1)
In [108]:
f([6, 8, 10])
Out[108]:
8
In [109]:
f = itemgetter(2)
In [110]:
f([6, 8, 10])
Out[110]:
10
In [114]:
table = [[4, 5], 
         [6, 3], 
         [2, 5], 
         [6, 1]]
# sort by second column
def my_sort_key(item):
    print("my_sort_key invoked, item =", item)
    return (item[1], item[0], len(item))
sorted(table, key=my_sort_key)
my_sort_key invoked, item = [4, 5]
my_sort_key invoked, item = [6, 3]
my_sort_key invoked, item = [2, 5]
my_sort_key invoked, item = [6, 1]
Out[114]:
[[6, 1], [6, 3], [2, 5], [4, 5]]
In [ ]:
sorted