Python - Idioms + Tricks Flashcards

1
Q

Loop over dictionary

A

for key in dict:

print(key)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Loop over dictionary and delete something in dictionary

A

for key in dict.keys()
if key.startswith(‘some letter’):
del dict[key]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Loop over dictionary and access both keys and values

A

for key, value in dict.items():

print(key, value)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Loop over dictionary and access both keys and values (in a memory efficient way)

A

for key, value in dict.iteritems():

print(key, value)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Construct a dictionary from pairs (memory efficient way)

A

mydict = dict( izip( firstlist, secondlist) ) )

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Counting with dictionaries

From this:
colors = {‘red’, ‘green’, ‘red’, ‘blue’….}

You want this:
{‘blue’: 1, ‘green’: 2, ‘red’: 3}

A

d = {}
for color in colors:
d[color] = d.get(color, 0) + 1

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Grouping with dictionaries

We want to group by number of letters:
names = [‘mary’, ‘matt’, ‘rachel’, ‘mellissa’, ‘betty’, ‘raymond’]

A

d = defaultdict(list)
for name in names:
key = len(name)
d[key].append(name)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Clarify the readability of your function calls with keyword arguments

Try to make this better:
my_function( ‘somestring’, False, 20, True )

A

my_function( name=’somestring’, nameofcondition=False,

somenumber=20, nameofcondition2=True )

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Unpacking sequences

mylist = [ ‘mundy’, ‘reimer’, 28, …]

A

firstname, lastname, age = mylist

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

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
A
def fibonacci(n):
    x, y  = 0, 1
    for i in range(n):
        print(x)
        x, y = y, x+y
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

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
A

x, y = ( x + dx * t, y + dy * t )

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

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)
A

print( ‘, ‘.join(names) )

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

How to open and close files (the efficient way)

Rewrite the following:

f = open('data.txt')
try:
    data = f.read()
finally:
    f.close()
A
with open('data.txt') as f:
    data = f.read()
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

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) ] )

A

Take out the square brackets to turn it into a generator expression!

print( sum( i**2 for i in range(10) )

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

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
A
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!
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

How would we use an assert statement to check if an IF-statement or chunk in code is not working?

if condition == x:
do_blah()
else:
do_blah2()

A

if condition == x:
do_blah()
elif: condition == y
do_blah2()
else:
assert False, (‘Printing this should not happen
but if it does, the error is here’)

17
Q

What’s good style for comma placement in lists with respect to catching diffs in line changes in some version control software? Fix the below code:

names = [‘Alice’, ‘Bob’, ‘Dilbert’}

A

Make sure you put list elements on separate lines and always end in a comma so you can add or subtract an element on the fly and only highlight that line as a diif in code:

names: = [
                'Alice',
                'Bob',
                'Dilbert',
                ]
18
Q

What the benefit of using with statements in opening files, and how do we use it? Fix the below:

f = open(‘hello.txt’, ‘w’)

f. write(‘hello world’)
f. close()

A

The benefit is that WITH automatically closes a file after the interpreter exits that indentation of code, so if any error occurs when the file is open, then it still gets closed automatically afterwards no matter what.

with open('hello.txt', 'w') as f:
    f.write('hello world')
19
Q

What does a single leading underscore in python mean? Example:

_var

A

It’s convention only, but it’s a hint to tell the programmer that the variable or method is for internal use only. That means that that variable or method stays within the module and is never used outside of it when imported.

It is interesting to note that wildcard imports (eg - from some_module import * ), will NOT import the names of methods or variables with a leading underscore.

20
Q

What does a single trailer underscore in python mean?
Example:

var_

A

This is used just in case you have a name conflict and want to use that name. For example, if you want to have a variable named ‘class’, we can’t because that is a reserved word, but instead we can use ‘class_’ to use it. This is just a convention.

21
Q

What does a double leading underscore (dunder) in python mean?
Example:

__var

A

A double underscore prefix causes the python interpreter to rewrite the attribute name in order to avoid naming conflicts/collisions in subclasses. This is called name mangling.
For example:

class Test:
    def \_\_init\_\_(self):
        self.foo = 11
        self._bar = 23
        self.\_\_baz = 42

t = Test()
dir(T)
_____
If we call the dir() function to look at all the attributes of a class, we will notice that the variable got renamed to _Test__baz, and will not show up to be able to be accessed in the subclasses.

22
Q

What does the double leading+trailing underscore (dunder) in python mean?
Example:

__var__

A

Name mangling does NOT occur and the interpreter leaves these alone. These are called dunder methods or magic methods and are reserved for special use in the language, like __init__

23
Q

What does a single underscore by itself in python mean?
Example:

_

A

Per convention, a single stand-alone underscore is sometimes used to indicate that a variable is temporary or insignificant or not used (like in loops or unpacking).
Example:

for _ in range(32):
print(‘Hello World’)

24
Q

Sort a list of dictionaries, by a specific key-value pair.

ex) Sort animals by age:

> > > animals = [
… {‘type’: ‘penguin’, ‘name’: ‘Stephanie’, ‘age’: 8},
… {‘type’: ‘elephant’, ‘name’: ‘Devon’, ‘age’: 3},
… {‘type’: ‘puma’, ‘name’: ‘Moe’, ‘age’: 5},
… ]

A

It’s worth knowing about the optional keyword argument key that lets you specify a function that will be called on every element prior to sorting. Adding a function allows custom sorting rules, which are especially helpful if you want to sort more complex data types:

sorted(animals, key=lambda animal: animal[‘age’])

By passing in a lambda function that returns each element’s age, you can easily sort a list of dictionaries by a single value of each of those dictionaries. In this case, the dictionary is now sorted in ascending order by age.

25
Q

What’s a quick way to turn a list expression into a generator expression? Why would you do this?

Change the below into a generator expression:
\_\_\_\_\_
# find the sum of the first 1000 perfect squares

sum( [ i * i for i in range(1, 1001) ] )

A

Generator expressions save on memory resources. Just replace the brackets with parentheses to easily create a generator expression!

sum( ( i * i for i in range(1, 1001) ) )

Generator expressions are perfect for when you know you want to retrieve data from a sequence, but you don’t need to access all of it at the same time.

Instead of creating a list, the generator expression returns a generator object. That object knows where it is in the current state (for example, i = 49) and only calculates the next value when it’s asked for.

So when sum iterates over the generator object by calling .__next__() repeatedly, the generator checks what i equals, calculates i * i, increments i internally, and returns the proper value to sum. The design allows generators to be used on massive sequences of data, because only one element exists in memory at a time.