Skip to main content
TellaDev
Cheatsheets Python

35 entries

Python

Python reference covering built-ins, data structures, file I/O, comprehensions, and classes

35 commands

len(obj)
Return the number of items in a sequence or collection
len([1, 2, 3]) # 3
range(start, stop, step)
Generate a sequence of integers from start up to (not including) stop
list(range(0, 10, 2)) # [0,2,4,6,8]
enumerate(iterable)
Return (index, value) pairs when iterating over a sequence
for i, v in enumerate(['a','b']): ...
zip(a, b)
Combine two iterables into an iterator of tuples
list(zip([1,2], ['a','b'])) # [(1,'a'),(2,'b')]
map(fn, iterable)
Apply a function to every item in an iterable
list(map(str.upper, ['hi'])) # ['HI']
filter(fn, iterable)
Return items from an iterable for which the function returns True
list(filter(None, [0,1,'',2])) # [1,2]
sorted(iterable, key=fn, reverse=True)
Return a new sorted list with optional key function and order
sorted(names, key=len) # by length
isinstance(obj, type)
Check if an object is an instance of a class or type
isinstance(42, int) # True
lst.append(x)
Append an item to the end of a list
colors.append('blue')
lst.extend([x, y])
Extend a list by appending all items from an iterable
nums.extend([4, 5, 6])
lst.pop(index)
Remove and return the item at a given index (default: last)
last = stack.pop()
lst.sort(key=fn)
Sort a list in-place with an optional key function
words.sort(key=str.lower)
lst[1:4]
Slice a list from index 1 up to (not including) index 4
[10,20,30,40,50][1:4] # [20,30,40]
lst[::-1]
Reverse a list using slice notation
[1,2,3][::-1] # [3,2,1]
d.get('key', default)
Get a value by key, returning a default if the key doesn't exist
cfg.get('port', 8080)
d.items()
Return a view of (key, value) pairs in a dictionary
for k, v in user.items(): ...
d.update({'key': 'val'})
Update a dictionary with key-value pairs from another dict
config.update({'debug': True})
{**d1, **d2}
Merge two dictionaries into a new one (Python 3.5+)
{**defaults, **overrides}
d.setdefault('key', [])
Return the value for a key, setting it to a default if absent
groups.setdefault('admin', [])
str.split(' ')
Split a string into a list on a delimiter
'hello world'.split() # ['hello','world']
', '.join(lst)
Join a list of strings into a single string with a separator
', '.join(['a','b','c']) # 'a, b, c'
f"{name!r} is {age} years old"
F-string with repr conversion and expression interpolation
f"{name} scored {score:.1f}"
str.strip()
Remove leading and trailing whitespace from a string
' hello '.strip() # 'hello'
with open('file.txt', 'r') as f: data = f.read()
Open a file and read its entire contents using a context manager
data = open('config.json').read()
with open('file.txt', 'w') as f: f.write(data)
Open a file for writing and write data to it
f.write('Hello\n')
import json json.loads(text)
Parse a JSON string into a Python object
json.loads('{"a": 1}') # {'a': 1}
import csv csv.reader(f)
Read a CSV file row by row using the csv module
for row in csv.reader(f): print(row)
[x*2 for x in lst if x > 0]
List comprehension with transformation and filter condition
[n**2 for n in range(5)] # [0,1,4,9,16]
{k: v for k, v in d.items() if v}
Dict comprehension that filters out falsy values
{k: v for k, v in d.items() if v > 0}
{x for x in lst}
Set comprehension — creates a set of unique values
{w.lower() for w in words}
class MyClass: def __init__(self, x): self.x = x
Define a class with an initializer method
p = MyClass(10); print(p.x)
class Dog(Animal): pass
Create a class that inherits from another class
rex = Dog(); rex.speak()
@staticmethod def fn():
Define a static method that doesn't receive the class or instance
MyClass.helper() # no self needed
@classmethod def fn(cls):
Define a class method that receives the class as the first argument
obj = MyClass.from_dict(data)
@property def value(self):
Define a read-only property using the property decorator
print(circle.area) # no parens