Python Tips I Wish I Knew Earlier
List Comprehensions List comprehensions are one of Python’s most elegant features. Instead of: squares = [] for x in range(10): squares.append(x**2) You can write: squares = [x**2 for x in range(10)] Context Managers Always use context managers for file operations: # Good with open('file.txt', 'r') as f: content = f.read() # Avoid f = open('file.txt', 'r') content = f.read() f.close() F-Strings F-strings make string formatting much cleaner: name = "Alice" age = 30 message = f"My name is {name} and I'm {age} years old" The enumerate() Function When you need both index and value: items = ['apple', 'banana', 'cherry'] for index, item in enumerate(items): print(f"{index}: {item}") Dictionary Comprehensions Just like list comprehensions, but for dictionaries: ...