Python Notes
These are my public notes on python 3
These are my public notes on python 3
List
Cons operator. Python3 only. Careful that it needs to have value for (a). empty list is fine for (b)
a, *b = [1,2,3] # a == 1, b == [2,3]
a, *b, c = [1,2,3] #a == 1, b == [2], c == 3
Looping
coord = [(1,2), (4,5)]
for x,y in coord:
print(x)
for x,_ in coord:
print(x)
for i, p in enumerate( range(5,9) ):
print( i, p )
Range
range(5) # 0 to 4
range(1,5) # 1 to 4
range(0,4,2) # 0,2
list(range(5)) #convert to list
Slice
l[start:endEx:step]
# start default = 0
# end default = len(l)
# step default = 1
l = [0,1,2,3,4]
l[2:3] = [20,30] # [0,1,20,30,4]
l[0:0] = [-2,-1] # [-2,-1,0,1,2,3,4]
del l[0:2] # [2,3,4]
l[0:2] = [] # [2,3,4]
Concat
a, b = [1,2], [3,4]
a + b # [1,2,3,4]
b += [1] # append (or b.append(1))
a * 2 # [1,2,1,2]
# be careful of using * in nested. It’s the same instance
Sorted
list.sort() # in-place
sorted(list) # copy any iterable
# key = 1 param function to sort
# reverse = True
Iterable Comprehension
str = ‘abc’
[ord(str) for ch in str]
[ord(str) for ch in str if ch != ‘a’]
[Card(rank,suit) for suit in suits for rank in ranks]
# Also knows to dedup by itself, does not throw
{ k:v for k,v in country_codes if k < 66 or v < 66 }
Dict
#Iterate, python3
for k,v in dict.items():
print(k, v)
#Get or Default
dict.get(‘key’, 0)
dict.setdefault(‘key’, []).append(new_value)
#DefaultDict
d = collections.defaultdict(list)
d[key].append('a') # no need to instantiate list
Set
empty_set = set() # no literal syntax for empty set
new_set = Set(['a','b'])
new_set.add('c')
combinedSet = setA | setB
Boolean Values
These values are False, others are true
* None
* False
* 0, 0.0
* [], {}, ()
* __len() == 0
* __bool() == 0
Testing
python -m unittest (discover)
(works without discover for python3, prefix with test in py name, prefix with test_ for method name.
import unittest
class TestStringMethods(unittest.TestCase):
def setUp(self): #also: tearDown
pass
@classmethod
def setUpClass(cls): #also: tearDown
pass
def test_upper(self):
self.assertEqual(‘foo’.upper(), ‘FOO’)
Class
class NewClass(BaseClass):
def __init__(self, x, y):
self.x = x
self.y = y
@staticmethod
def method(no_self):
pass
Named Tuples
from collections import namedtuple
Student = namedtuple(‘Student’, ‘firstname lastname’)
a = Student(‘first’, ‘last’)
a.firstname
a.lastname
a = Student(first=’first’, last=’last’)
a._make( (‘a’,’b’) )
a._asdict()
a.first
Enum
Don’t forget to import unique, auto keyword. auto is available in python 3.6
from enum import Enum, unique, auto
@unique
class Color(Enum):
RED = 1 #auto()
GREEN = 2 #auto()
BLUE = 3 #auto()
Swap values
a,b = b,a
Tuple unpacking for functions
v = (1,2)
sum(*v)
String Format
'%s %s' % ('one', 'two')
'{} {}'.format('one', 'two')
'{0} {1}'.format('one', 'two')
'{:>10}'.format('test') # right
'{:10}'.format('test') # left
'{:.5}'.format('xylophone') # trunc
'{:d}'.format(42)
'{:06.2f}'.format(3.141592653589793)
'{:%Y-%m-%d %H:%M}'.format(datetime(2001, 2, 3, 4, 5))
Naming Conventions
module_name, package_name
method_name, function_name, function_parameter_name
ClassName, ExceptionName,
GLOBAL_CONSTANT_NAME,
instance_var_name, global_var_name, local_var_name