Python basics
Everyday Python: types, collections, comprehensions, functions and common idioms.
25 cardsBeginnerCode
Download the deck Get StackCards
Open the downloaded file on your iPhone or iPad and choose StackCards. It is also in the app: Library tab, then Add to my library.
What is inside
Print a valueWrites text to the console.
print("Hello")Make a listOrdered, changeable, and allows duplicates.
numbers = [1, 2, 3]
Make a dictionaryMaps keys to values.
ages = {"Ana": 30, "Luis": 25}Make a tupleOrdered and unchangeable.
point = (4, 7)
Make a setUnordered collection of unique items.
tags = {"a", "b", "a"} # {'a', 'b'}Loop with an indexenumerate gives the position and the item together.
for i, name in enumerate(names):
print(i, name)Loop over two lists togetherzip pairs items up and stops at the shortest.
for a, b in zip(xs, ys):
print(a, b)List comprehensionBuilds a list from an expression in one line.
squares = [n * n for n in range(5)]
Comprehension with a filterAdds a condition at the end.
evens = [n for n in nums if n % 2 == 0]
Dictionary comprehensionBuilds a dict the same way.
lengths = {w: len(w) for w in words}Define a functiondef, a name, parameters and a return value.
def add(a, b=0):
return a + bAccept any number of arguments*args collects positionals, **kwargs collects keywords.
def f(*args, **kwargs):
...Anonymous functionA small function without a name.
double = lambda x: x * 2
Format a stringAn f-string puts values straight into the text.
f"{name} is {age}"Read a file safelywith closes the file even if something fails.
with open("data.txt") as f:
text = f.read()Handle an errorCatch a specific exception and keep going.
try:
int(text)
except ValueError:
print("not a number")Define a classMethods take self as the first parameter.
class Dog:
def __init__(self, name):
self.name = nameSlice a liststart:stop:step, where stop is not included.
nums[1:4] # items 1, 2, 3 nums[::-1] # reversed
Check if a key exists safelyget returns a default instead of raising KeyError.
ages.get("Eva", 0)Sort a list by a rulekey says what to compare.
people.sort(key=lambda p: p.age)
Swap two variablesTuple unpacking needs no temporary.
a, b = b, a
Truthy and falsyEmpty collections, 0, None and "" count as False; most else is True.
== vs is== compares values. is checks whether both names point to the very same object.
Mutable vs immutableLists, dicts and sets can change in place. Strings, tuples and numbers can't.
What is a generator?A function that yields values one at a time instead of building the whole list in memory.