In [1]:
import this
Beautiful is better than ugly
In [8]:
def filter_modulo(items, modulo):
output_items = []
for i in range(len(items)):
if items[i] % modulo:
output_items.append(items[i])
return output_items
In [ ]:
def filter_modulo(items, modulo):
for item in items:
if item % modulo:
yield item
In [ ]:
Flat is better than nested
In [2]:
def print_matrices():
for matrix in matrices:
print('Matrix:')
for row in matrix:
for col in row:
print(col, end='')
print()
print()
In [3]:
def print_row(row):
for col in row:
print(col, end='')
def print_matrix(matrix):
for row in matrix:
print_row(row)
print()
def print_matrices(matrices):
for matrix in matrices:
print('Matrix:')
print_matrix(matrix)
print()
Sparse is better than dense
In [4]:
def make_eggs(a,b):'while',['technically'];print('correct');{'this':'is','highly':'unreadable'};print(1-a+b**4/2**2)
In [5]:
make_eggs(1, 2)
In [6]:
def make_eggs(a, b):
'while', ['technically']
print('correct')
{'this': 'is', 'highly': 'unreadable'}
print(1 - a + ((b ** 4) / (2 ** 2)))
In [7]:
make_eggs(1, 2)
Differences between value and identity comparisons
In [10]:
a = 200 + 56
b = 256
c = 200 + 57
d = 257
print('%r == %r: %r' % (a, b, a == b))
print('%r is %r: %r' % (a, b, a is b))
print('%r == %r: %r' % (c, d, c == d))
print('%r is %r: %r' % (c, d, c is d))
The catch is that Python keeps an internal array of integer objects for all integers between -5 and 256 ; that's why it works for 256 but not for 257.
The basic guideline is that when comparing Python singletons such as True, False , and None, always compare using is.
In [11]:
spam = range(1000000)
eggs = range(1000000)
In [12]:
spam == eggs
Out[12]:
In [15]:
spam is eggs # similar to use id(...)
Out[15]:
In [16]:
id(spam) == id(eggs)
Out[16]:
Loops
In [18]:
i = 0
my_list = []
while i < len(my_list):
item = my_list[i]
i += 1
do_something(i, item)
In [19]:
# Do the same as above
for i, item in enumerate(my_list):
do_something(i, item)
In [23]:
def spam(key, value, list_=[], dict_={}):
list_.append(value)
dict_[key] = value
print('List: %r' % list_)
print('Dict: %r' % dict_)
spam('key 1', 'value 1')
spam('key 2', 'value 2')
Enquanto o output esperado seria:
List: ['value 1']
Dict: {'key 1': 'value 1'}
List: ['value 2']
Dict: {'key 2': 'value 2'}
The reason is that list and dict are actually shared between multiple calls. The only time this is actually useful is if you are doing something hacky, so please avoid using mutable objects as default parameters in a function.
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]: