Categories:Viewed: 6 - Published at: a few seconds ago

Don't use mutable objects as default arguments for functions!

def append_to_list(value, def_list=[]):
    def_list.append(value)
    return def_list
my_list = append_to_list(1)
print(my_list)

my_other_list = append_to_list(2)
print(my_other_list)

args and sleep

import time
def report_arg(my_default=time.time()):
    print(my_default)
report_arg()
time.sleep(5)
report_arg()

List are mutable

a_list = []
print('ID:', id(a_list))
a_list += [1]
print('ID (+=):', id(a_list))
a_list = a_list + [2]
print('ID (list = list + ...):', id(a_list))

All blank lists are not the same

a_list = []
print(a_list, '\nID (initial):',id(a_list), '\n')
a_list.append(1)
print(a_list, '\nID (append):',id(a_list), '\n')
a_list.extend([2])
print(a_list, '\nID (extend):',id(a_list))

True and False in the datetime module

from platform import python_version
import datetime

print("Current python version: ", python_version())
print('"datetime.time(0,0,0)" (Midnight) ->', bool(datetime.time(0,0,0))) ### Python version <= 3.4.5 evaluates this statement to False

Python reuses objects for small integers - use "==" for equality, "is" for identity

a = 1
b = 1
print('a is b', bool(a is b))
c = 999
d = 999
print('c is d', bool(c is d))

equality operator works this way

print('256 is 257-1', 256 is 257-1)
print('257 is 258-1', 257 is 258 - 1)
print('-5 is -6+1', -5 is -6+1)
print('-7 is -6-1', -7 is -6-1)

illustrate the test for equality (==) vs. identity (is)

a = 'hello world!'
b = 'hello world!'
print('a is b,', a is b)
print('a == b,', a == b)

We would think that identity would always imply equality, but this is not always true, as we can see in the next example:

a = float('nan')
print('a is a,', a is a)
print('a == a,', a == a)

Shallow copy in python

list1 = [1,2]
list2 = list1        # reference
list3 = list1[:]     # shallow copy
list4 = list1.copy() # shallow copy
print('IDs:\nlist1: {}\nlist2: {}\nlist3: {}\nlist4: {}\n'
      .format(id(list1), id(list2), id(list3), id(list4)))

Deepcopy in python

list1 = [[1],[2]]
list2 = list1.copy()    # shallow copy
list3 = deepcopy(list1) # deep copy
print('IDs:\nlist1: {}\nlist2: {}\nlist3: {}\n'
      .format(id(list1), id(list2), id(list3)))

logical or logical and

result = (2 or 3) * (5 and 7)
print('2 * 7 =', result)

Generators are consumed

gen = (i for i in range(5))
print('2 in gen,', 2 in gen)
print('3 in gen,', 3 in gen)
print('1 in gen,', 1 in gen) 

Convert generator to a list

gen = (i for i in range(5))
a_list = list(gen)

Usage of bool class

print('isinstance(True, int):', isinstance(True, int))

Create list of numbers using lambda function but not the right way

my_list = [lambda: i for i in range(5)]
for l in my_list:
    print(l())

print the numbers properly by creating a list

my_list = [lambda x=i: x for i in range(5)]
for l in my_list:
    print(l())

local scope representation

x = 0
def in_func():
    x = 1
    print('in_func:', x)

Global Scope Representation

x = 0
def in_func1():
    x = 1
    print('in_func1:', x)
print('global:', x)

Usage of global keyword

x = 0
def in_func2():
    global x
    x = 1
    print('in_func2:', x)
in_func2()
print('global:', x)

local vs. enclosed

def outer():
    x = 1
    print('outer before:', x)

    def inner():
        x = 2
        print("inner:", x)
    inner()
    print("outer after:", x)
outer()

nonlocal keyword comes in handy

def outer():
    x = 1
    print('outer before:', x)

    def inner():
        nonlocal x
        x = 2
        print("inner:", x)
    inner()
    print("outer after:", x)
outer()

tuples are immutable

tup = (1,)
tup[0] += 1