Skip to content

Latest commit

History

History
78 lines (69 loc) · 10.4 KB

File metadata and controls

78 lines (69 loc) · 10.4 KB

Python Cheat Sheet

With the help of my little friend (Copilot)

Data Types and Data Structures

TypeMutableOrderedAllows duplicatesConstructorExampleCollection ofNoteCategory
intNoint()-5Note: int is a whole numberdata type
floatNofloat()3.27Note: float is a decimal numberdata type
complexNocomplex()1 + 2jNote: complex is a complex numberdata type
boolNobool()TrueNote: bool is a boolean value; it's a subclass of intdata type
strNoYesYes'' or ""'hello', """hello"""charactersNote: str is a sequence of charactersdata type
listYesYesYes[][1, 'two', 3.0]elementsNote: lists are mutable sequencesdata structure
tupleNoYesYes()(1, 'two', 3.0)elementsNote: tuples are immutable listsdata structure
setYesNoNo{}{1, 2, 3}elementsNote: set also uses {} but it does not contain key-value pairsdata structure
dictYesNoNo{}{'key1': 1.0, 'key2': False}key-value pairsNote: dict also uses {} but it does not contain elementsdata structure

Collections like Counter, namedtuple, OrderedDict, defaultdict, deque (as well as UserDict and ChainMap)

CollectionDescriptionExample
CounterA dict subclass for counting hashable objects.Counter('hello')
namedtupleFactory function for creating tuple subclasses with named fields.Point = namedtuple('Point', ['x', 'y'])
p = Point(1, y=2)
p[0] + p[1]
OrderedDictA dict subclass that remembers the order entries were added.OrderedDict([('a', 1), ('b', 2), ('c', 3)])
OrderedDict({'a': 1, 'b': 2, 'c': 3})
defaultdictA dict subclass that calls a factory function to supply missing values.defaultdict(int, {'a': 1, 'b': 2, 'c': 3})
defaultdict(lambda: 2, {'a': 1, 'b': 2})
dequeA list-like sequence optimized for data accesses near its endpoints.deque('hello', maxlen=5)
UserDictA wrapper around dictionary objects for easier dict subclassing.UserDict({'a': 1, 'b': 2, 'c': 3})
ChainMapA class for creating a single view of multiple mappings.ChainMap({'a': 1, 'b': 2}, {'b': 3, 'c': 4})

Operators

OperatorDescriptionExample
len(s)Length of slen('hello')
s[i]ith item of s, origin 0'hello'[1]
s[i:j]Slice of s from i to j'hello'[1:4]
s[i:j:k]Slice of s from i to j with step k'hello'[1::2]
x in sTrue if x is an item of s'e' in 'hello'
x not in sTrue if x is not an item of s'e' not in 'hello'
s + tConcatenation of s and t'hello' + ' ' + 'world!'
s * nn copies of s'hello' * 3
s[i] = xItem i of s is replaced by xs = 'hello'; s[1] = 'a'
s[i:j] = tSlice of s from i to j is replaced by the contents of the iterable ts = 'hello'; s[1:3] = 'xyz'
del s[i:j]Same as s[i:j] = []s = 'hello'; del s[1:3]
s[i:j:k] = tThe elements of s[i:j:k] are replaced by those of ts = 'hello'; s[1:5:2] = 'xyz'
del s[i:j:k]Same as s[i:j:k] = []s = 'hello'; del s[1:5:2]
s.append(x)Appends x to the end of the sequence (same as s[len(s):len(s)] = [x])s = [1, 2, 3]; s.append(4)
s.clear()Removes all items from s (same as del s[:])s = [1, 2, 3]; s.clear()
s.copy()Creates a shallow copy of s (same as s[:])s = [1, 2, 3]; t = s.copy()
s.extend(t)Appends the contents of t to s (same as s[len(s):len(s)] = t)s = [1, 2, 3]; t = [4, 5, 6]; s.extend(t)
s *= nUpdates s with its contents repeated n timess = [1, 2, 3]; s *= 2
s.insert(i, x)Inserts x into s at the index given by i (same as s[i:i] = [x])s = [1, 2, 3]; s.insert(1, 4)
s.pop([i])Retrieves the item at i and also removes it from ss = [1, 2, 3]; s.pop(1)
s.remove(x)Removes the first item from s where s[i] == xs = [1, 2, 3]; s.remove(2)
s.reverse()Reverses the items of s in places = [1, 2, 3]; s.reverse()
s.sort([key], [reverse])Sorts the items of s in places = [1, 2, 3]; s.sort()

Math Operations

OperationDescriptionExample
x + ySum of x and y3 + 2
x - yDifference of x and y3 - 2
x * yProduct of x and y3 * 2
x / yQuotient of x and y3 / 2
x // yFloored quotient of x and y3 // 2
x % yRemainder of x / y3 % 2
-xx negated-3
+xx unchanged+3
abs(x)Absolute value or magnitude of xabs(-3)
int(x)x converted to integerint('3')
float(x)x converted to floatfloat(3)
complex(re, im)A complex number with real part re, imaginary part im. im defaults to 0.complex(3, 2)
c.conjugate()Conjugate of the complex number ccomplex(3, 2).conjugate()
divmod(x, y)The pair ((x-x%y)/y, x%y)divmod(3, 2)
pow(x, y) or x ** yx to the power of ypow(3, 2) or 3 ** 2