5.1 Back to Python basics¶
As today's lesson will be a bit more complex in terms of Python, we will start by discussing the technical fundamentals of the language.
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!
Simple data types¶
Integer¶
x = 5
x.__class__
int
Float¶
x = 1.2
x.__class__
float
Bool¶
x = 2>3
x.__class__
bool
String¶
x = 'alfa'
x.__class__
str
Container data types¶
List
List items are ordered, mutable, and allow duplicate values. List items are indexed, the first item has index [0], the second item has index [1] etc.
x = [1,1.2,'alfa',True]
x.__class__
list
x.append('d')
x
[1, 1.2, 'alfa', True, 'd']
Tuple
Tuple items are ordered, immutable, and allow duplicate values. Tuple items are indexed, the first item has index [0], the second item has index [1] etc.
x = (1,2,3,4)
x.__class__
tuple
Set
Set items are unordered, immutable, and do not allow duplicate values.
x = {'a','b','c','a','b','a'}
x.__class__
set
Dictionary
Dictionary items are ordered, mutable, and does not allow duplicates. Dictionary items are presented in key:value pairs, and can be referred to by using the key name.
x = {'alfa':5,'beta':3,'gama':2}
x.__class__
dict
x['beta']
3
x.keys()
dict_keys(['alfa', 'beta', 'gama'])
x.values()
dict_values([5, 3, 2])
x.items()
dict_items([('alfa', 5), ('beta', 3), ('gama', 2)])
Functions¶
def f1(x, y):
"""
Function computes...
x: atribute 1....
y: atribute 2.....
return: ....
"""
z = x**y
return z
In newer Python versions we can use named notations.
def f1(x:int,y:int)->int:
"""
Function computes...
x: atribute 1....
y: atribute 2.....
return: ....
"""
z = x**y
return z
help(f1)
Help on function f1 in module __main__: f1(x: int, y: int) -> int Function computes... x: atribute 1.... y: atribute 2..... return: ....
print(f1.__doc__)
Function computes... x: atribute 1.... y: atribute 2..... return: ....
f1.__annotations__
{'x': int, 'y': int, 'return': int}
What is Lambda function?¶
Regular function
%%timeit -n 100
def count(x):
return x*10
count(10)
The slowest run took 25.05 times longer than the fastest. This could mean that an intermediate result is being cached. 1.78 µs ± 3.14 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
Lambda is anonymous function. It is faster than regular function because we do not have to create function object. We need keyword lambda, put arguments on one side (x), then :, and finally we put expression we want to evaluate (x*10).
%%timeit -n 100
(lambda x:x*10)(10)
297 ns ± 8.21 ns per loop (mean ± std. dev. of 7 runs, 100 loops each)
What is a list comprehension?¶
Regular way of adding rows to the list
%%timeit -n 100
num = []
for i in range(10):
if i%2 == 0:
num.append(i)
num
3.22 µs ± 1.76 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
Pythonic way of adding rows to the list using comprehension
%%timeit -n 100
num = [i for i in range(10) if i%2 == 0 ]
num
The slowest run took 7.47 times longer than the fastest. This could mean that an intermediate result is being cached. 5.07 µs ± 4.44 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)