REF: Python Cheat Sheet


Data structures

Arithmetic operations

3 // 2                         # 1 rounded down integer value
3 % 2                          # 1  remainder of division
int(3.9)                       # = 3

Logic

Automatically evaluates to False: None, 0 (integer), 0.0 (real), empty strings, and objects of container types. The and operator has higher precedence than the or operator.

Strings

st, s = "aaa", 'aa'

st.strip()                     # removes leading and trailing whitespace (returns a new string)
st.lower()                     # converts to lowercase
st.upper()                     # converts to uppercase

st.startswith(s)               # checks if it starts with string s (True, False)
st.endswith(s)                 # checks if it ends with string s (True, False)
st.find(s)                     # returns the index of the found occurrence (int)
s in st                        # checks if s is contained within st (True, False)

st.replace(s1,s2)              # replaces all occurrences of s1 with s2

','.join(["F", "B", "I"])      # joins elements of the list with a comma as separator

Memory

Strings, numbers are immutable objects
y = x = 3
s1, s2, i1, i2 = "aaa",  "aaa", 1, 1

x  is y                        # True (refer to the same memory location)
s1 is s2                       # True
i1 is i2                       # True
[3] is [3]                     # False
id(x)                          # 2546626711664 (memory address)

Lists

lst = [1, 2, 3]
lst.append(4)                  # [1, 2, 3, 4] returns nothing, modifies lst
lst.insert(2, 4)               # [1, 2, 4, 3] (at position 2, shifts elements to the right)
[1, 2, 3] + [4, 5]             # [1, 2, 3, 4, 5] concatenation
lst.extend([4, 5])             # same as above but more efficient (?)

lst.pop()                      # 4 [1, 2, 3] removes the last element, returning it
lst.pop(1)                     # 2 [1, 3, 4]  removes the element at index 1, returning it
lst.remove(2)                  # removes the first occurrence of 2 (raises exception if not found)
lst.reverse()                  # reverses the list

1 in lst                       # checks if 1 is in the list

lst.sort()                     # sorts the list lexicographically (elements must be comparable)
lst.sort(reverse = True)       # sorts in reverse order
lst.sort(key = lambda x: x%2)  # [1,2,3,4] -> [2,4,1,3]

lst = list( filter(lambda x: x % 2, lst) )# [1,2,3,4] -> [1,3]
lst = list( filter(None, tokens) )        # ['a','','b'] -> ['a','b'] removes empty strings

Set

Elements must be hashable (numbers, strings, but not lists)
hash('a')                      # -5021022557028035767
s = {'a','a','b'}              # {'b','a'} order is not defined, values are unique
'a' in s                       # membership check

Associative arrays

Performs the operation t[hash('x')] and checks if the returned value is not None.
t = {'x' : 1, 'y' : 2}
t['x'] = 3                     # if 'x' key does not exist, raises an exception; otherwise, updates the value
t.get('x')                     # returns None if key does not exist, otherwise returns the value

'x' in t                       # checks if key exists
t.keys(), t.values()           # returns keys and values

for k, v in t.items():         # iterates over key-value pairs
    print(k) if v > 5 else None


Control and functions

Loops and branching

for i in [0, 1, 2]:         j = 0                if x > 3:    print("Big")
   print(i)                 while j < 3:         elif x == 3: print("Medium")
                               j = j + 1         else:        print("Small")

Functions

def f(x, y=2):
   return x*y

f = lambda x,y: x+y            # lambda arguments : returned expression
z = f(2,3)

List comprehension and map

lst = [x**2 for x in range(10)]

lst = [(1,2), (3,4)]
[x for x,y in lst if y > 2]    # [1]

[(x, y) for x in range(3) for y in range(3)])

([line.strip() for line in open("readFile.py")]

[[x for x in line.split() if len(x) > 3] for line in text.split('\n')]
The function map() applies a function to each element of an iterable object. If there are multiple objects, it stops calculation after reaching the end of the shortest object:
list(map(lambda x: 2*x, [1,2,3]))          # [2, 4, 6]

txt = ['girl like boy', 'boy is programmer']
mark = list( map(lambda s: (True, s) if 'girl' in s else (False, s), txt) )

powers = list(map(pow, [2,3], [1, 2, 3]))  # [2, 9] = 2**1, 3**2


Slices

s = [0, 1, 2, 3, 4]            # list
s[:]                           # copy of the list (new memory)
s[1:]                          # [1, 2, 3, 4]  all except the first element
s[-3:]                         # [2, 3, 4]     last 3 elements
s[1:4:2]                       # [1, 3]        step 2 from index 1 to 4

del s[1:3]                     # s = [0, 3, 4] deletion
s[1:4:2]=list("ab")            # s = [0,'a',2,'b',4] replacement

"Hello!"[2:4]                  # 'll'          lists, strings, tuples
"Hello!"[::-1]                 # '!olleH'      reversal
In order for objects to understand slice, you need to define the methods методы __getitem__, __setitem__, __delitem__ (the attributes of key can be None, so you need to check for that):
class MySliceble():
    def __getitem__(self, key):
        if isinstance(key, slice):
            return list(range(key.start, key.stop, key.step))
        else:
            raise Exception("Trying to access by index")
my = MySliceble()
my[2:9:2]                            # [2, 4, 6, 8]