Python Basics
Python Miscellaneous Syntax
1. Comprehensions
A compact, one-line way to create a list, set, or dictionary from a loop.
List Comprehension
# Traditional way
lst = []
for i in range(1, 11):
lst.append(i)
# List comprehension — same result
lst = [i for i in range(1, 11)] # → [1, 2, 3, ..., 10]
With an expression
lst = [i / 2 for i in range(1, 11)] # → [0.5, 1.0, 1.5, ...]
With a condition (filter)
lst = [i / 2 for i in range(1, 11) if i % 2 == 0] # only even numbers
With a nested loop
lst = [i * j for i in range(1, 11) for j in range(5)]
Set Comprehension
Use curly braces {} — duplicates are automatically removed.
s = {i for i in range(1, 11)} # → {1, 2, 3, ..., 10}
Dictionary Comprehension
Use curly braces with a key: value pair.
d = {i: j for i in range(1, 11) for j in range(5)}
⚠️ Tuple Comprehension Doesn't Exist
Using () creates a generator object, not a tuple.
(i for i in range(10)) # → generator object (NOT a tuple)
# To get a tuple, use list comprehension then convert:
tuple([i for i in range(10)])
2. Multiple Assignment
Assign the same value to multiple variables in one line.
x = y = 1 # both x and y equal 1
x = y = z = 2 # x, y, and z all equal 2
3. Unpacking
Unpack an iterable (tuple, list) into individual variables. The number of variables must match the number of elements.
x, y = 1, 2 # x = 1, y = 2 (right side is a tuple)
x, y, z = 1, 2, 3 # x = 1, y = 2, z = 3
x, y = [10, 20] # works with lists too
This is the same mechanism used when a function returns multiple values — the returned tuple gets unpacked.
4. Doc Strings
A doc string is a description comment placed at the top of a function (or class), written as a triple-quoted string.
def foo():
"""This is the foo function."""
pass
def add(x, y):
"""
Returns the sum of x and y.
Both x and y should be numbers.
"""
return x + y
help() — Read a Doc String
help(foo) # prints the doc string of foo
help(len) # → "Return the number of items in a container."
help(max) # → full documentation for max()
help()works on any function, class, or data type. PressCtrl+Cto stop if output is very long.
Cheat Sheet
# List comprehension
[i for i in range(1, 11)]
[i * 2 for i in range(1, 11)]
[i for i in range(1, 11) if i % 2 == 0]
[i * j for i in range(5) for j in range(5)]
# Set comprehension
{i for i in range(1, 11)}
# Dictionary comprehension
{i: i * 2 for i in range(1, 11)}
# Tuple comprehension — doesn't work, use this instead:
tuple([i for i in range(10)])
# Multiple assignment
x = y = z = 0
# Unpacking
x, y = 1, 2
x, y, z = [10, 20, 30]
# Doc string
def my_func():
"""Describe what this function does."""
pass
help(my_func)