Python Basics
Dynamic Typing
In Python, the type of a variable is determined at run time.
Type Annotation
age: int = 20
age = "Python"
Lists
my_list = ['a','b','c']
my_list.append('d')
my_list[1:] # ['b', 'c', 'd']
my_list[:1] # ['a']
nest = [1,2,3,[4,5,['target']]]
nest[3][2] # ['target']
nest[3][2][0] # 'target'
list comprehension
x = [1,2,3,4]
out = []
for item in x:
out.append(item**2)
print(out) # [1, 4, 9, 16]
[item**2 for item in x] # [1, 4, 9, 16]
Dictionaries
d = {'key1':'item1','key2':'item2'}
d['key1'] # 'item1'
Tuples
t = (1,2,3)
t[0] # 1
Sets
{1,2,3,1,2,1,2,3,3,3,3,2,2,2,1,1,2} # {1, 2, 3}
if
if 1 > 2:
print('first')
else:
print('last')
if 1 == 2:
print('first')
elif 3 == 3:
print('middle')
else:
print('Last')
for Loops
seq = [1,2,3,4,5]
for item in seq:
print(item)
while Loops
i = 1
while i < 5:
print('i is: {}'.format(i))
i = i+1
range()
for i in range(5):
print(i)
list(range(5)) # [0, 1, 2, 3, 4]
functions
def my_func(param1='default'):
"""
Docstring goes here.
"""
print(param1)
def square(x):
return x**2
lambda expressions
x = lambda a : a + 10
print(x(5))
x = lambda a, b : a * b
print(x(5, 6))
x = lambda a, b, c : a + b + c
print(x(5, 6, 2))
map & filter
seq = [1,2,3,4,5]
list(map(lambda var: var*2,seq)) # [2, 4, 6, 8, 10]
methods
st = 'hello my name is Sam'
st.lower()
st.upper()
st.split() # ['hello', 'my', 'name', 'is', 'Sam']
d = {'key1': 'item1', 'key2': 'item2'}
d.keys() # dict_keys(['key2', 'key1'])
d.items() # dict_items([('key2', 'item2'), ('key1', 'item1')])
lst = [1,2,3]
lst.pop() # 3
lst # [1, 2]
'x' in ['x','y','z'] # True