Skip to content

Instantly share code, notes, and snippets.

@alexandremcosta
Created July 28, 2024 20:59
Show Gist options
  • Save alexandremcosta/1b58079a1e56e4b839e0bd1872d64938 to your computer and use it in GitHub Desktop.
Save alexandremcosta/1b58079a1e56e4b839e0bd1872d64938 to your computer and use it in GitHub Desktop.
Python Cheatsheet
# List Comprehensions
squares = [x**2 for x in range(10)]
even_squares = [x**2 for x in range(10) if x % 2 == 0]
# Dictionary Comprehensions
squared_dict = {x: x**2 for x in range(10)}
# Lambda Functions
add = lambda a, b: a + b
# List Methods
lst = [1, 2, 3, 4]
lst.append(5)
lst.remove(3)
lst.sort(reverse=True)
lst.reverse()
# Dictionary Methods
d = {'key1': 'value1', 'key2': 'value2'}
d.update({'key3': 'value3'})
value = d.get('key1', 'default')
keys = d.keys()
values = d.values()
items = d.items()
# Set Methods
s = {1, 2, 3, 4}
s.add(5)
s.remove(3)
union = s.union({6, 7})
intersection = s.intersection({2, 3})
difference = s.difference({1, 2})
# String Methods
s = "hello world"
s_upper = s.upper()
s_lower = s.lower()
s_replace = s.replace("world", "Python")
s_split = s.split()
s_find = s.find("hello")
s_count = s.count("l")
# Map, Filter, Reduce
from functools import reduce
mapped = list(map(lambda x: x*2, [1, 2, 3]))
filtered = list(filter(lambda x: x > 1, [1, 2, 3]))
reduced = reduce(lambda x, y: x + y, [1, 2, 3])
# Enumerate
for index, value in enumerate(['a', 'b', 'c']):
print(index, value)
# List Slicing
lst = [1, 2, 3, 4, 5]
sub_lst = lst[1:3]
rev_lst = lst[::-1]
# Advanced Functions
def my_function(p1, p2="default"):
"""Function Documentation"""
return p1 + p2
# Generators
def my_generator():
for i in range(10):
yield i
# Context Managers
with open('file.txt', 'r') as file:
data = file.read()
# Exception Handling
try:
x = 1 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
finally:
print("This always executes")
# Modules
import math
import random
import itertools
# Math
sqrt = math.sqrt(16)
fact = math.factorial(5)
# Random
randint = random.randint(1, 10)
choice = random.choice([1, 2, 3, 4])
# Itertools
permutations = list(itertools.permutations([1, 2, 3]))
combinations = list(itertools.combinations([1, 2, 3], 2))
product = list(itertools.product([1, 2], repeat=2))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment