Review of fundamentals B#
In this notebook, you will review the additional python syntax we’ve covered since the first review of fundamentals. You should be able to correctly predict what happens in all of these cases. If you get something wrong, figure out why!
Lists, list comprehension, and randomization#
my_list = ['spam']
print(len(my_list))
print(len(my_list[0]))
1
4
print(list(range(10)[-5:]))
[5, 6, 7, 8, 9]
import random
my_list = ['a','b','c']*3 + ['c','d','e']*3
random.shuffle(my_list)
my_list[0:5]
Show code cell output
['b', 'b', 'c', 'c', 'd']
import random
my_list = ['a','b','c'] + ['c','d','e']
random.sample(my_list,7)
Show code cell output
['d', 'e', 'c', 'a', 'c']
import random
[round(random.random(),1) for i in range(15)]
Show code cell output
[0.8, 0.5, 0.4, 0.1, 0.4, 0.5, 0.7, 0.2, 0.4, 0.8, 0.0, 0.3, 0.4, 0.0, 0.9]
vowels = ['a', 'e', 'i','o','u']
print ([element*i for i,element in enumerate(vowels)])
Show code cell output
['', 'e', 'ii', 'ooo', 'uuuu']
print (' '.join([' '.join((i, 'and a')) for i in ('one', 'two', 'three', 'four')]))
Show code cell output
one and a two and a three and a four and a
responses = 'ccctcctttttcc'
[i for i,curResp in enumerate(responses) if curResp=='c']
Show code cell output
[0, 1, 2, 4, 7, 12, 13, 14, 17, 19, 20, 21, 22, 24, 26, 28, 29, 30]
import random
positions = ['left', 'middle', 'right']
positions2 = positions
positions.append('bottom')
random.shuffle(positions2)
print (positions, positions2)
print (len(positions), len(positions2))
print (positions==positions2)
Show code cell output
['middle', 'right', 'bottom', 'left'] ['middle', 'right', 'bottom', 'left']
4 4
True
Dictionaries#
positions = {'left':(-100,0), 'middle':(0,0), 'right':(100,0)}
[random.choice(list(positions.keys())) for i in range(10)]
Show code cell output
['left',
'left',
'left',
'left',
'middle',
'middle',
'left',
'middle',
'middle',
'middle']
Note
In Python 2, dict.keys() returned a list. In Python 3 it returns a ‘view’ object which is fine if you want to see what the keys are, but won’t work for subsetting or doing things like getting choosing a random element as we do here. To make it work, we must force it to be a list with list()
positions = {'left':(-100,0), 'middle':(0,0), 'right':(100,0)}
[positions[random.choice(list(positions.keys()))] for i in range(10)]
Show code cell output
[(0, 0),
(100, 0),
(100, 0),
(0, 0),
(100, 0),
(0, 0),
(100, 0),
(-100, 0),
(-100, 0),
(0, 0)]
responses = 'ccctcctttttcc'
responsesMapping = {'c':'chair','t':'table'}
[responsesMapping[curResp] for curResp in responses]
Show code cell output
['chair',
'chair',
'chair',
'table',
'chair',
'chair',
'table',
'table',
'table',
'table',
'table',
'chair',
'chair']