In [1]:
import this


The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

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)


correct
4.0

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)


correct
4.0

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


256 == 256: True
256 is 256: True
257 == 257: True
257 is 257: False

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]:
True

In [15]:
spam is eggs # similar to use id(...)


Out[15]:
False

In [16]:
id(spam) == id(eggs)


Out[16]:
False

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


List: ['value 1']
Dict: {'key 1': 'value 1'}
List: ['value 1', 'value 2']
Dict: {'key 1': 'value 1', '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 [ ]: