Python Cheat Sheet - Function
Function | Example | Description |
---|---|---|
List | l = [1, 2, 3] print(len(l)) # 3 |
A container data type that stores a sequence of elements. Unlike strings, lists are mutable: modification possible. |
Adding elements | [1, 2, 3].append(4) # [1, 2, 3, 4] [1, 2, 3].insert(2,2) # [1, 2, 2, 3] [1, 2, 3] + [4] # [1, 2, 3, 4] |
Add elements to a list with (i) append, (ii) insert, or (iii) list concatenation. The append operation is very fast. |
Removal | [1, 2, 3, 4].remove(1) # [2, 3, 4] |
Removing an element can be slower. |
Reversing | [1, 2, 3].reverse() # [3, 2, 1] |
This reverses the order of list elements. |
Sorting | [2, 4, 3].sort() # [2, 3, 4] |
Sorts a list. The computational complexity of sorting is O(n log n) for n list elements. |
Indexing | [2, 4, 3].index(2) # index of element 4 is "0" [2, 4, 3].index(2,1) # index of element 2 after pos 1 is "1" |
Finds the first occurrence of an element in the list & returns its index. Can be slow as the whole list is traversed. |
Stack | stack = [3] stack.append(42) # [3, 42] stack.pop() # 42 (stack: [3]) stack.pop() # 3 (stack: []) |
Python lists can be used intuitively as stack via the two list operations append() and pop(). |
Set | basket = {'apple', 'eggs', 'banana', 'orange'} |
A set is an unordered collection of elements. Each can exist only once. |
Dictionary | calories = {'apple': 52, 'banana': 89, 'choco': 546} |
The dictionary is a useful data structure for storing (key, value) pairs. |
Reading and writing elements | print(calories['apple'] < calories['choco']) # True calories['capu'] = 74 print(calories['banana'] < calories['capu']) # False print('apple' in calories.keys()) # True print(52 in calories.values()) # True |
Read and write elements by specifying the key within the brackets. Use the keys() and values() functions to access all keys and values of the dictionary. |
Dictionary Looping | for k, v in calories.items(): print(k) if v > 500 else None # 'chocolate' |
You can loop over the (key, value) pairs of a dictionary with the items() method. |
Membership operator | basket = {'apple', 'eggs', 'banana', 'orange'} print('eggs' in basket) # True print('mushroom' in basket) # False |
Check with the 'in' keyword whether the set, list, or dictionary contains an element. Set containment is faster than list containment. |
List and Set Comprehension | # List comprehension l = [i * i for i in [1, 2, 3]] # Set comprehension squares = {x**2 for x in [0,2,4] if x < 4} |
List comprehension is the concise Python way to create lists. Use brackets plus an expression, followed by a for clause. Close with zero or more for or if clauses. Set comprehension is similar to list comprehension. |
Reference Image: function