Python (2022-10-17)

Modules

[1]:
import sys
[2]:
type(sys)
[2]:
module
[3]:
try:
    sys.exit()
except SystemExit:
    pass
[4]:
my_sys = sys
del sys
[5]:
my_sys.byteorder
[5]:
'little'
[6]:
import sys as my_sys
[7]:
import sys
[8]:
sys.byteorder
[8]:
'little'
[9]:
from sys import byteorder
[10]:
byteorder
[10]:
'little'
[11]:
from sys import *    # all of dir(sys)
[12]:
exit
[12]:
<function sys.exit(status=None, /)>

Tuple Unpacking, Lists Iteration, And Such

Tuple Unpacking

[13]:
a = 1
b = 2
[14]:
tmp = a
a = b
b = tmp
print(a, b)
2 1
[15]:
a = 1
b = 2
[16]:
a, b = b, a
[17]:
print(a, b)
2 1
[18]:
def function_returns_two_values():
    return 42, 666
[19]:
rv = function_returns_two_values()
rv
[19]:
(42, 666)
[20]:
a, b = function_returns_two_values()
a, b
[20]:
(42, 666)

… On Lists of Pairs

[21]:
l = [(1, 'one'), (2, 'two')]
[22]:
for elem in l:
    print(elem)
(1, 'one')
(2, 'two')
[23]:
for elem in l:
    x = elem[0]
    y = elem[1]
    print(x, y)
1 one
2 two
[24]:
for x, y in l:
    print(x, y)
1 one
2 two
[25]:
for _, y in l:
    print(y)
one
two

Dictionaries

[26]:
l = [(1, 'one'), (2, 'two')]
[27]:
d = {1: 'one',
    2:'two'
    }
[28]:
d = dict(l)
[29]:
d
[29]:
{1: 'one', 2: 'two'}
[30]:
d[1]
[30]:
'one'
[31]:
d[3] = 'three'
[32]:
len(d)
[32]:
3
[33]:
for elem in d:
    print(elem)
1
2
3
[34]:
for elem in d.keys():
    print(elem)
1
2
3
[35]:
for v in d.values():
    print(v)
one
two
three
[36]:
for k, v in d.items():
    print(k, v)
1 one
2 two
3 three

Variables, Types

[37]:
i = 42
[38]:
type(i)
[38]:
int
[39]:
i = 'abc'
[40]:
type(i)
[40]:
str
[41]:
i = [1,2,3, 'abc', {1:'one'}]
[42]:
type(i)
[42]:
list
[43]:
a = 42
id(a)
[43]:
140134238766608
[44]:
b = a
id(b)
[44]:
140134238766608

sizeof()

[45]:
dir(float)
[45]:
['__abs__',
 '__add__',
 '__bool__',
 '__ceil__',
 '__class__',
 '__delattr__',
 '__dir__',
 '__divmod__',
 '__doc__',
 '__eq__',
 '__float__',
 '__floor__',
 '__floordiv__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__getformat__',
 '__getnewargs__',
 '__gt__',
 '__hash__',
 '__init__',
 '__init_subclass__',
 '__int__',
 '__le__',
 '__lt__',
 '__mod__',
 '__mul__',
 '__ne__',
 '__neg__',
 '__new__',
 '__pos__',
 '__pow__',
 '__radd__',
 '__rdivmod__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__rfloordiv__',
 '__rmod__',
 '__rmul__',
 '__round__',
 '__rpow__',
 '__rsub__',
 '__rtruediv__',
 '__setattr__',
 '__setformat__',
 '__sizeof__',
 '__str__',
 '__sub__',
 '__subclasshook__',
 '__truediv__',
 '__trunc__',
 'as_integer_ratio',
 'conjugate',
 'fromhex',
 'hex',
 'imag',
 'is_integer',
 'real']
[46]:
import sys
sys.getsizeof(3.14)
[46]:
24
[47]:
f = 3.14
f.__sizeof__()
[47]:
24
[48]:
bin(0b0010^0b1011)
[48]:
'0b1001'

Compound Datatypes

List

[49]:
l = [1,2,3]
[50]:
l.append(4)
[51]:
l
[51]:
[1, 2, 3, 4]
[52]:
l.append('fuenf')
[53]:
l.extend([6,7,8])
[54]:
l
[54]:
[1, 2, 3, 4, 'fuenf', 6, 7, 8]
[55]:
del l[2]
l
[55]:
[1, 2, 4, 'fuenf', 6, 7, 8]

Tuple

[56]:
t = (1,2,3)
[57]:
try:
    t.append(4)
except AttributeError as e:
    print(e)
'tuple' object has no attribute 'append'

Dictionary

[58]:
d = {1:'one', 2:'two'}
[59]:
d[1]
[59]:
'one'
[60]:
try:
    print(d[3])
except KeyError as e:
    print('nix')
nix
[61]:
value = d.get(3)
if value is True:
    print(value)
else:
    print('nix')
nix
[62]:
d['vier'] = 4
[63]:
d
[63]:
{1: 'one', 2: 'two', 'vier': 4}
[64]:
key_list = [1,2,3]
try:
    d[key_list] = 666
except TypeError as e:
    print(e)
unhashable type: 'list'
[65]:
key_tuple = (1,2,3)
d[key_tuple] = 42

Set

[66]:
s = {1,2,3}
[67]:
3 in s
[67]:
True
[68]:
5 in s
[68]:
False
[69]:
s.add(5)
[70]:
5 in s
[70]:
True

Immutable? References?

[71]:
l1 = [1,2,3,4,5]
l2 = l1
[72]:
l1 == l2    # same content
[72]:
True
[73]:
l1 is l2
[73]:
True
[74]:
id(l1) == id(l2)
[74]:
True
[75]:
l1.append(6)
l2
[75]:
[1, 2, 3, 4, 5, 6]
[76]:
l3 = l1[:]    # allocate new list, and copy toplevel
[77]:
l3 == l1
[77]:
True
[78]:
l3 is l1
[78]:
False
[79]:
l3.append(7)
[80]:
l1
[80]:
[1, 2, 3, 4, 5, 6]
[81]:
l3
[81]:
[1, 2, 3, 4, 5, 6, 7]
[82]:
evil_list = [1,2,3,[4,5,6],7,8,9]
[83]:
len(evil_list)
[83]:
7
[84]:
evil_list_2 = evil_list[:]
[85]:
evil_list_2.append(10)
[86]:
evil_list
[86]:
[1, 2, 3, [4, 5, 6], 7, 8, 9]
[87]:
evil_list_2[3].append(100)
[88]:
evil_list
[88]:
[1, 2, 3, [4, 5, 6, 100], 7, 8, 9]

Strings

[89]:
s = 'abc'
s
[89]:
'abc'
[90]:
s = "abc"
s
[90]:
'abc'
[91]:
s = 'ab"c'
s
[91]:
'ab"c'
[92]:
s = "ab\"c"
s
[92]:
'ab"c'
[93]:
doc = '''
das ist eine doku von
einem modul, das blah
viel zu kompliziert ist,
um in eine zeile zu passen.
'''
[94]:
doc
[94]:
'\ndas ist eine doku von \neinem modul, das blah \nviel zu kompliziert ist,\num in eine zeile zu passen.\n'

Tuple Unpacking

[95]:
l = [{'id': 1, 'firstname': 'Joerg'}, {'id': 2, 'firstname': 'Caro'}]
[96]:
for elem in l:
    print(elem)
{'id': 1, 'firstname': 'Joerg'}
{'id': 2, 'firstname': 'Caro'}
[97]:
for id, firstname in l:
    print(id, firstname)
id firstname
id firstname
[98]:
d = {'id': 1, 'firstname': 'Joerg'}
[99]:
x, y = d
print(x, y)
id firstname
[100]:
x, y = d.keys()
[101]:
x, y
[101]:
('id', 'firstname')
[102]:
x, y = d.values()
x, y
[102]:
(1, 'Joerg')

Raw Strings

\U is a unicode escape sequence

[103]:
# Syntax error: doze_path = 'D:\Users\blah'
[104]:
doze_path = 'D:\\Users\\blah'
doze_path
[104]:
'D:\\Users\\blah'
[105]:
doze_path = r'D:\Users\blah'
doze_path
[105]:
'D:\\Users\\blah'
[106]:
regex = r'^[0-9]*\.txt'
import re
[107]:
compiled_regex = re.compile(regex)
[108]:
compiled_regex.search('123.txt')
[108]:
<re.Match object; span=(0, 7), match='123.txt'>

JSON

[109]:
l = [{'id': 1, 'firstname': 'Joerg'}, {'id': 2, 'firstname': 'Caro'}]
[110]:
import pprint
pprint.pprint(l, width=10)
[{'firstname': 'Joerg',
  'id': 1},
 {'firstname': 'Caro',
  'id': 2}]
[111]:
import json
[112]:
l_json = json.dumps(l)
l_json
[112]:
'[{"id": 1, "firstname": "Joerg"}, {"id": 2, "firstname": "Caro"}]'
[113]:
l_json_sent = l_json
[114]:
received_data = json.loads(l_json_sent)
received_data
[114]:
[{'id': 1, 'firstname': 'Joerg'}, {'id': 2, 'firstname': 'Caro'}]

Iteration

[115]:
l = [666, 42.5,3, 'abc']
[116]:
for elem in l:
    print(elem)
666
42.5
3
abc

Index based iteration

[117]:
for i in range(len(l)):
    print(i, l[i])
0 666
1 42.5
2 3
3 abc
[118]:
for i, elem in enumerate(l):
    print(i, elem)
0 666
1 42.5
2 3
3 abc

Iterable?

[119]:
for elem in l:
    print(elem)
666
42.5
3
abc
[120]:
d = {1:'one', 2:'two'}
for elem in d:
    print(elem)
1
2
[121]:
s = {666, 1.5, 'abc'}
for elem in s:
    print(elem)
1.5
abc
666
[122]:
s = 'Joerg'
for elem in s:
    print(elem)
J
o
e
r
g
[123]:
i = 666
try:
    for elem in i:
        print(elem)
except TypeError as e:
    print(e)
'int' object is not iterable
[124]:
l = list('Joerg')
l
[124]:
['J', 'o', 'e', 'r', 'g']

lists from dictionaries

[125]:
d
[125]:
{1: 'one', 2: 'two'}
[126]:
list(d)
[126]:
[1, 2]
[127]:
list(d.values())
[127]:
['one', 'two']

And range()?

[128]:
for i in range(5):
    print(i)
0
1
2
3
4
[129]:
r = range(5)
r
[129]:
range(0, 5)
[130]:
it = iter(r)
[131]:
it
[131]:
<range_iterator at 0x7f73869f06c0>
[132]:
next(it)
[132]:
0
[133]:
next(it)
[133]:
1
[134]:
next(it)
[134]:
2
[135]:
next(it)
[135]:
3
[136]:
next(it)
[136]:
4
[137]:
try:
    next(it)
except StopIteration:
    pass
[138]:
for i in range(5):
    print(i)
0
1
2
3
4
[139]:
it = iter([1,2,3])
next(it)
[139]:
1
[140]:
next(it)
[140]:
2
[141]:
next(it)
[141]:
3
[142]:
try:
    next(it)
except StopIteration:
    pass

More About Dictionaries

[143]:
d = {
    'one': 1,
    'two': 2,
}
[144]:
d
[144]:
{'one': 1, 'two': 2}
[145]:
d['three'] = 3
[146]:
d['two'] = 200
[147]:
d
[147]:
{'one': 1, 'two': 200, 'three': 3}
[148]:
2 in d
[148]:
False
[149]:
if 2 in d:
    d[2] += 100
[150]:
d
[150]:
{'one': 1, 'two': 200, 'three': 3}
[151]:
try:
    d[100]
except KeyError as e:
    print(e)
100
[152]:
value = d.get(100)
print(value)
None
[153]:
value = d.get(100)
if value is None:
    d[100] = 'hundred'
[154]:
d
[154]:
{'one': 1, 'two': 200, 'three': 3, 100: 'hundred'}

collections.defaultdict

[155]:
from collections import defaultdict
[156]:
d = defaultdict(int)
[157]:
d[100]
[157]:
0
[158]:
def create_avg_items():
    return [0,0]
[159]:
d = defaultdict(create_avg_items)
[160]:
d = defaultdict(lambda: [0,0])
[161]:
elem = d['sensor1']
elem
[161]:
[0, 0]
[162]:
elem[0] += 3.14
elem[1] += 1
[163]:
d['sensor1']
[163]:
[3.14, 1]

More About Lists

[164]:
l = [3,2,5,6,7]
[165]:
l.append(42)
l
[165]:
[3, 2, 5, 6, 7, 42]
[166]:
l1 = ['a', 'b']
l.append(l1)
[167]:
l
[167]:
[3, 2, 5, 6, 7, 42, ['a', 'b']]
[168]:
del l[len(l)-1]
[169]:
l1 = ['a', 'b']
l.append(l1)
[170]:
l
[170]:
[3, 2, 5, 6, 7, 42, ['a', 'b']]
[171]:
l[-1:] = []
l
[171]:
[3, 2, 5, 6, 7, 42]
[172]:
l1 = ['a', 'b']
l.append(l1)
l
[172]:
[3, 2, 5, 6, 7, 42, ['a', 'b']]
[173]:
l.pop(len(l)-1)
[173]:
['a', 'b']
[174]:
l
[174]:
[3, 2, 5, 6, 7, 42]
[175]:
l1
[175]:
['a', 'b']
[176]:
l.extend(l1)
l
[176]:
[3, 2, 5, 6, 7, 42, 'a', 'b']
[177]:
try:
    l.sort()
except TypeError as e:
    print(e)
'<' not supported between instances of 'str' and 'int'
[178]:
l = [3,2,5,6,7]
[179]:
l.sort()
l
[179]:
[2, 3, 5, 6, 7]
[180]:
l = [3,2,5,6,7]
[181]:
sorted(l)
[181]:
[2, 3, 5, 6, 7]
[182]:
l
[182]:
[3, 2, 5, 6, 7]

More About Dictionaries

[183]:
d = {}
[184]:
type(d)
[184]:
dict
[185]:
d = dict()
[186]:
l = [(1, 'one'), [2, 'two']]
d = dict(l)
d
[186]:
{1: 'one', 2: 'two'}
[187]:
l = ('zero', 'one', 'two')
for i, name in enumerate(l):
    print(i, name)
0 zero
1 one
2 two
[188]:
l = ('zero', 'one', 'two')
d = dict(enumerate(l))
d
[188]:
{0: 'zero', 1: 'one', 2: 'two'}
[189]:
d[100] = 'hundred'
d
[189]:
{0: 'zero', 1: 'one', 2: 'two', 100: 'hundred'}
[190]:
d[100]
[190]:
'hundred'
[191]:
try:
    d[99]
except KeyError as e:
    print(e)
99
[192]:
value = d.get(99)
if value is not None:
    print(value)
else:
    print('leider nein')
leider nein
[193]:
value = d.get(99, 'leider nein')
print(value)
leider nein
[194]:
del d[100]
d
[194]:
{0: 'zero', 1: 'one', 2: 'two'}

Iteration

[196]:
d
[196]:
{0: 'zero', 1: 'one', 2: 'two'}
[202]:
for elem in d:
    print(elem)
0
1
2
[203]:
list(d)
[203]:
[0, 1, 2]
[204]:
for k in d.keys():
    print(k)
0
1
2
[205]:
for v in d.values():
    print(v)
zero
one
two
[206]:
list(d.values())
[206]:
['zero', 'one', 'two']
[209]:
dict(enumerate(d.values()))
[209]:
{0: 'zero', 1: 'one', 2: 'two'}
[211]:
for elem in d.items():
    print(elem)
(0, 'zero')
(1, 'one')
(2, 'two')
[212]:
list(d.items())
[212]:
[(0, 'zero'), (1, 'one'), (2, 'two')]
[213]:
d.setdefault(99, 'ninetynine')
[213]:
'ninetynine'
[214]:
d[99]
[214]:
'ninetynine'
[215]:
d[1]
[215]:
'one'
[216]:
d.setdefault(1, 'eins')
[216]:
'one'
[218]:
if 100 in d:
    result = d[100]
else:
    d[100] = 'hundred'
    result = 'hundred'
print(result)
hundred
[219]:
d
[219]:
{0: 'zero', 1: 'one', 2: 'two', 99: 'ninetynine', 100: 'hundred'}
[220]:
del d[100]
[221]:
result = d.setdefault(100, 'hundred')
result
[221]:
'hundred'
[222]:
d
[222]:
{0: 'zero', 1: 'one', 2: 'two', 99: 'ninetynine', 100: 'hundred'}