Python 3 is the world’s most popular programming language for web development, cloud automation, data engineering, and artificial intelligence. Mastering Python data structures, list comprehensions, context managers, and standard library modules allows developers to write clean, idiomatic code.
Understanding how Python handles memory allocation, sequence slicing, dictionary hashtables, and generator streams ensures that your code runs efficiently while remaining easy to read and maintain.
Key Takeaways
- Master core data structures: mutable Lists, immutable Tuples, key-value Dictionaries, and unique Sets.
- Use list, dict, and set comprehensions alongside generator expressions for memory-efficient iteration.
- Always wrap file streams in `with open(...) as f:` context managers to guarantee clean handle cleanup.
- Leverage `match-case` structural pattern matching (Python 3.10+) and type annotations for readable code.
What are Python’s core primitive data types, lists, tuples, and strings?
Python primitives include integers, floats, strings, booleans, and None. Lists are ordered mutable sequences, while tuples are ordered immutable containers. F-strings allow inline variable evaluation, formatting specifiers, and string method execution directly within literal text blocks.
Primitives & Strings
x = 42 # int
pi = 3.14159 # float
name = "Alice" # str
is_valid = True # bool
data = None # NoneType
# F-String Formatting & Methods
f"Hello, {name}!" # "Hello, Alice!"
name.lower() # "alice"
name.upper() # "ALICE"
name.strip() # removes whitespace
"a,b,c".split(",") # ["a", "b", "c"]
"-".join(["a", "b"])# "a-b"Lists & Tuples
lst = [10, 20, 30]
lst.append(40) # Add element to end
lst.insert(1, 15) # Insert 15 at index 1
lst.pop() # Remove and return last element (40)
lst.remove(20) # Remove first occurrence of 20
lst[0:2] # Slice first two items [10, 15]
# Tuples (Immutable)
point = (10, 20)
x, y = point # Unpack tuple valuesHow do Python Dictionaries and Sets manage key-value pairs and unique items?
Dictionaries store key-value mappings with fast O(1) hash lookups, while Sets maintain unordered collections of unique elements. Using the .get() method when looking up dictionary keys prevents runtime KeyError exceptions when handling dynamic API responses.
Dictionaries
d = {"name": "Alice", "age": 30}
d["name"] # "Alice"
d.get("email") # None (safe lookup, no KeyError)
d.get("email", "N/A") # "N/A" (returns default if missing)
d["city"] = "Mumbai" # Add key-value pair
del d["age"] # Delete key
"name" in d # True
d.keys() # dict_keys(["name", "city"])
d.values() # dict_values(["Alice", "Mumbai"])
d.items() # dict_items([("name", "Alice"), ...])
d.pop("city") # Remove and return value
# Dictionary Comprehension
squares = {x: x**2 for x in range(5)}Sets & Set Operations
s = {1, 2, 3, 3} # {1, 2, 3} — duplicate elements are removed automatically
s.add(4)
s.remove(2) # Remove item (raises KeyError if missing)
s.discard(99) # Remove item safely (no error if missing)
a = {1, 2, 3}
b = {2, 3, 4}
a | b # Union: {1, 2, 3, 4}
a & b # Intersection: {2, 3}
a - b # Difference: {1}
a ^ b # Symmetric Difference: {1, 4}How do Python control flow, functions, classes, and exceptions work?
Control flow structures loops and conditionals, functions encapsulate reusable logic, and classes implement Object-Oriented Programming (OOP). Using with open() context managers guarantees file resource cleanup even if exceptions are raised during execution.
Control Flow & Loops
# Conditionals & Ternary Operator
label = "positive" if x > 0 else "non-positive"
# Loops & Enumeration
for i, item in enumerate(["a", "b", "c"]):
print(f"Index {i}: {item}")
# Dictionary Iteration
for key, value in d.items():
print(f"{key} => {value}")Functions & Object-Oriented Classes
# Function with default args, *args, **kwargs, and type hints
def calculate(name: str, *args, **kwargs) -> float:
return sum(args)
# Classes & Inheritance
class Animal:
def __init__(self, name: str):
self.name = name
def speak(self) -> str:
return f"{self.name} makes a noise."
class Dog(Animal):
def speak(self) -> str:
return f"{self.name} barks!"File I/O & Exception Handling
# Safe File Handling with Context Managers
with open("file.txt", "r") as f:
content = f.read()
# Exception Handling Block
try:
result = 10 / 0
except ZeroDivisionError as e:
print(f"Caught error: {e}")
finally:
print("Cleanup operations completed.")What are Python built-ins, comprehensions, and standard library modules?
Comprehensions provide concise syntax for creating collections, while standard modules (os, sys, json, re, datetime) supply built-in utilities. Utilizing generator expressions instead of list comprehensions avoids allocating massive arrays in memory when iterating over large datasets.
Built-in Helper Functions Reference
| Function | Action |
|---|---|
len(seq) | Return total item count |
enumerate(seq) | Return tuple iterator of (index, value) |
zip(a, b) | Aggregate elements from two or more iterables |
map(fn, seq) | Apply function lazily across sequence |
filter(fn, seq) | Filter elements lazily based on boolean predicate |
sum(seq) / min(seq) / max(seq) | Compute total sum, minimum, or maximum value |
sorted(seq) | Return a new sorted list from sequence |
isinstance(obj, type) | Verify object type inheritance |
Standard Library Quick Reference
import os, sys, json, re
from datetime import datetime
# Environment & Path Operations
os.getcwd() # Get current working directory
os.path.exists("file.txt") # Check file existence
# System & Arguments
sys.argv # Access CLI script arguments
# JSON Parsing
json_str = json.dumps({"key": "val"}) # Convert dict to JSON string
data_dict = json.loads(json_str) # Parse JSON string into dict
# Regular Expressions
re.findall(r"\d+", "Item 10 and 20") # Returns ["10", "20"]
# Datetime Formatting
now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")Frequently Asked Questions
What is the difference between a List and a Tuple in Python?
Lists are mutable (you can add, edit, or remove items), defined using square brackets []. Tuples are immutable (read-only once created), defined using parentheses ().
When should I use a generator expression instead of a list comprehension?
Use generator expressions (x for x in seq) when processing large datasets where you iterate only once. Generators stream items on-demand, consuming O(1) memory compared to list comprehensions [x for x in seq] which build full arrays in RAM.
What to Read Next
- Linux Bash Cheat Sheet: Commands & Scripting — Shell automation scripts.
- cURL Command-Line Cheat Sheet — Test REST and JSON APIs.
- Zero-Cost Claude Code + Ollama Setup Guide — Run local LLMs for Python coding.



