A quick cheatsheet on python operations
Slice:
astring = "Hello World" print(astring[3:7]) # prints-> lo w print(astring[0:10:2]) # skips one character, prints -> Hlowr print(astring[::-1]) # reverse a string using step -1
Case
astring.upper() astring.lower()
Slicing complete list performs a copy
spam_copy = spam[:]
Zip to loop
furniture = ['table', 'chair', 'rack', 'shelf'] price = [100, 50, 80, 40] for item, amount in zip(furniture, price): print(f'The {item} costs ${amount}')
Multiple assignments
furniture = ['table', 'chair', 'rack', 'shelf'] table, chair, rack, shelf = furniture
find in list =
furnitures.index('chaiur')
Sort:
reverse sort =
furniture.sort(reverse=True)
sorted
returns a new list, and accepts any iterable.list.sort()
sorts in place, only works for lists.key
function passed for custom sort>>> letters = ['a', 'z', 'A', 'Z'] >>> letters.sort(key=str.lower) >>> letters # ['a', 'A', 'z', 'Z'] >>> sorted(letters, key=str.lower) # also same
tuples are compared lexicographically; the first items are compared; if they are the same then the second items are compared, and so on.
Tuples:
tuples
are immutable objects,lists
are mutable.Tuples are more memory efficient
Dictionary
>>> for key in pet.keys(): >>> for value in pet.values(): >>> for key, value in pet.items(): >>> pet.setdefault('has_hair', True) # merge dictionaries >>> dict_c = {**dict_a, **dict_b}
Set
>>> s = {1, 2, 3} >>> s = set([1, 2, 3]) >>> s.add(4) >>> s.update([2, 3, 4, 5, 6]) #add multiple >>> s.remove(3) # raises errors >>> s.discard(3) # does NOT raise errors >>> s1.union(s2) # or 's1 | s2' >>> s1.intersection(s2, s3) # or 's1 & s2 & s3' >>> s1.difference(s2) # or 's1 - s2' >>> s1.symmetric_difference(s2) # or 's1 ^ s2' all the elements that are not common between them.
Comprehension
# LIST COMPREHENSION >>> new_list = [n for n in names] >>> n = [(a, b) for a in range(1, 3) for b in range(1, 3)] # [(1, 1), (1, 2), (2, 1), (2, 2)] >>> new_list = [n for n in names if n.startswith('C')] # SET COMPREHENSION >>> {s.upper() for s in b} # DICT COMPREHENSION >>> {v: k for k, v in c.items()}
Strings
>>> ', '.join(['cats', 'rats', 'bats'])
References
lists and tuples: sheet
Another useful pdf : mementopython3-english.pdf