Python cheat sheet

Use the adapted type

A dict is not an ordered type. If you need an ordered dict, use a more advanced collection type like the ordered dict:

>>> from collections import OrderedDict
>>> d = OrderedDict({'banana': 3, 'apple': 4, 'pear': 1, 'orange': 2})
>>> d
OrderedDict([('orange', 2), ('apple', 4), ('banana', 3), ('pear', 1)])
>>>

Careful about Mutable types and non-mutable types

A set is immutable, whereas a list is mutable:

>>> s = set([1,2])
>>> l = [1,2]
>>> l.append(3)
>>> list(l)
[1, 2, 3]
>>> s.append(3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'set' object has no attribute 'append'
>>>

A string is immutable. If you want to modify it, build another string:

>>> s = "hello"
>>> s.replace('ll', 'bb')
'hebbo'
>>> s+"you"
'helloyou'
>>> s
'hello'

Base type are objects

It means that in python, classes are types (let’s understand it like that at first glance)

>>> a = 2
>>> isinstance(a, int)
True
>>> s = "a"
>>> dir(s)
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__',
'__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__',
(...)
'__init__', '__iter__', '__le__', '__len__', '__lt__', ]

s has methods. It’s an objects. The type of s is the class int.

>>> d = {'banana': 3, 'apple': 4, 'pear': 1, 'orange': 2}
>>> isinstance(d, dict)
True
>>>

Important

But a base type doesn’t have attributes.

>>> a = 2
>>> a.a = 5
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'int' object has no attribute 'a'
>>>

If you want attributes in types you have to inherit from the base types:

>>> class A(int): pass
...
>>> a = A()
>>> a.a = 5
>>>