Python - Idioms + Tricks Flashcards
Loop over dictionary
for key in dict:
print(key)
Loop over dictionary and delete something in dictionary
for key in dict.keys()
if key.startswith(‘some letter’):
del dict[key]
Loop over dictionary and access both keys and values
for key, value in dict.items():
print(key, value)
Loop over dictionary and access both keys and values (in a memory efficient way)
for key, value in dict.iteritems():
print(key, value)
Construct a dictionary from pairs (memory efficient way)
mydict = dict( izip( firstlist, secondlist) ) )
Counting with dictionaries
From this:
colors = {‘red’, ‘green’, ‘red’, ‘blue’….}
You want this:
{‘blue’: 1, ‘green’: 2, ‘red’: 3}
d = {}
for color in colors:
d[color] = d.get(color, 0) + 1
Grouping with dictionaries
We want to group by number of letters:
names = [‘mary’, ‘matt’, ‘rachel’, ‘mellissa’, ‘betty’, ‘raymond’]
d = defaultdict(list)
for name in names:
key = len(name)
d[key].append(name)
Clarify the readability of your function calls with keyword arguments
Try to make this better:
my_function( ‘somestring’, False, 20, True )
my_function( name=’somestring’, nameofcondition=False,
somenumber=20, nameofcondition2=True )
Unpacking sequences
mylist = [ ‘mundy’, ‘reimer’, 28, …]
firstname, lastname, age = mylist
Updating multiple state variables at once
Make the below better:
def fibonacci(n): x = 0 y = 1 for i in range(n): print(x) temp = y y = x+y x = temp
def fibonacci(n): x, y = 0, 1 for i in range(n): print(x) x, y = y, x+y
Simultaneous state variable updates (especially when doing a differential equation where the variables in a equation update at time steps)
Make the below better (get rid of temp variables):
temp_x = x + dx * t temp_y = y + dy * t x = temp_x y = temp_y
x, y = ( x + dx * t, y + dy * t )
Concatenating strings (the efficient way)
Rewrite the following:
names = ['mundy', 'bob', 'alice', 'bill'] s = names[0] for name in names[1:]: s+= ', ' + name print(s)
print( ‘, ‘.join(names) )
How to open and close files (the efficient way)
Rewrite the following:
f = open('data.txt') try: data = f.read() finally: f.close()
with open('data.txt') as f: data = f.read()
Turn List expressions into Generator Expressions (so it doesn’t have to create the whole list at once and be memory intensive)
Rewrite the following:
print( sum( [ i**2 for i in range(10) ] )
Take out the square brackets to turn it into a generator expression!
print( sum( i**2 for i in range(10) )
In the following function definition, how would we use an ASSERT statement to help us debug in the case something goes wrong? What does the ASSERT statement return if it is true/false?
def apply_discount (price, discount): price_after_discount = price * (1.0 - discount)
return price_after_discount
def apply_discount (price, discount): price_after_discount = price * (1.0 - discount) assert 0 <= price_after_discount <= price return price_after_discount \_\_\_\_\_\_ If the assert statement is TRUE, nothing happens. If it is FALSE (and the price after discount happens to be lower than 0 dollars or higher than the original price), then the assert statement raises an AssertionError as an exception, along with an optional error message. Use ASSERT statements for debugging (in case things go wrong) only! Don't ever use them as an alternative for an if statement or anything logic or program flow wise. Debugging only!