Python Loops, Everyday Syntax and the Standard Library #1.3
A for loop walks the items directly. Slicing, comprehensions and the standard library keep data handling short without installing anything.
On this page (14)
- Loops, everyday syntax and the standard library
- Loops: for, range, enumerate, zip, while
- Python syntax you meet every day
- The standard library you use daily
- Counting and grouping: Counter, defaultdict
- Queues: deque
- Time: datetime, zoneinfo
- JSON
- Paths: pathlib
- Logs: logging
- Regex: re
- Named constants: enum
- Key takeaways
- Sources
Loops, everyday syntax and the standard library
What does the code below print?
from collections import Counter
courses = ["Redis", "Python", "Redis"]
for i, name in enumerate(courses):
print(i, name)
# prints:
# 0 Redis
# 1 Python
# 2 Redis
print([n.lower() for n in courses if n != "Python"])
# prints: ['redis', 'redis']
print(Counter(courses))
# prints: Counter({'Redis': 2, 'Python': 1})
for walks the items directly, a comprehension filters and transforms in one line, and Counter from the standard library counts without writing a loop. The whole lesson is about three things: looping, writing it short, and using what ships with Python.
| Section | Example | Result |
|---|---|---|
| Loops | enumerate(courses) | 0 Redis, 1 Python, 2 Redis |
| Everyday syntax | [n.lower() for n in courses if n != "Python"] | ['redis', 'redis'] |
| Standard library | Counter(courses) | Counter({'Redis': 2, 'Python': 1}) |
Loops: for, range, enumerate, zip, while
Python's for walks the items directly. There is no for (i = 0; i < n; i++), no i++ and no do ... while.
| Write | Meaning | Result |
|---|---|---|
for x in items: | walk each item of a list, tuple, string or set | |
range(3), range(1, 10, 2) | numbers from start up to, not including, stop, by step | 0 1 2, 1 3 5 7 9 |
enumerate(items) | pairs of (position, item) | (0, 'Redis'), (1, 'Python') |
zip(a, b) | pairs items from two sequences, stopping at the shorter one | ('Redis', 12), ('Python', 6) |
d.items() | walk a dict as key, value pairs | ('apple', 3) |
while condition: | repeat while the condition is true | |
break, continue | leave the loop; skip the rest of this pass |
courses = ["Redis", "Python"]
lessons = [12, 6]
for i, course in enumerate(courses):
print(i, course)
# prints:
# 0 Redis
# 1 Python
for course, count in zip(courses, lessons):
print(course, count)
# prints:
# Redis 12
# Python 6
stock = {"apple": 3, "pear": 0}
for item, qty in stock.items():
if qty == 0:
continue
print(item, qty)
# prints: apple 3
print(list(range(1, 10, 2)))
# prints: [1, 3, 5, 7, 9]
n = 3
while n > 0:
n -= 1
print(n)
# prints: 0
n -= 1isn = n - 1.list(range(...))is only there to print the numbers;rangeitself does not build a list, it produces each number when asked.
Python syntax you meet every day
The examples below share this data: a = [10, 20, 30, 40, 50], d1 = {"a": 1}, x = 5.
| Write | Meaning | Result |
|---|---|---|
a[-1] | last item | 50 |
a[1:3] | slicing: from index 1 up to, not including, 3 | [20, 30] |
a[::-1] | reversed (step -1) | [50, 40, 30, 20, 10] |
first, *rest = a | unpacking | first = 10, rest = [20, 30, 40, 50] |
{**d1, "b": 2} | merge dicts | {'a': 1, 'b': 2} |
[x * 2 for x in a if x > 20] | list comprehension: filter and transform | [60, 80, 100] |
lambda x: x * 2 | one-expression anonymous function | a function; called with 5 it returns 10 |
0 < x < 10 | chained comparison | True |
if (n := len(a)) > 3: | walrus: assign inside an expression (3.8) | n = 5, the condition is true |
Compared with other languages: the same job in JS, Java and Go.
| Job | JS | Java | Go |
|---|---|---|---|
| last item | a.at(-1) | a.get(a.size() - 1) | a[len(a)-1] |
| slicing | a.slice(1, 3) | a.subList(1, 3) | a[1:3] |
| reversed | [...a].reverse() | Collections.reverse | write a loop |
| unpacking | const [first, ...rest] = a | none | none |
| merge dicts | {...d1, b: 2} | putAll | copy in a loop |
| list comprehension | filter().map() | stream().filter().map() | a loop |
| lambda | x => x * 2 | x -> x * 2 | func(x int) int { return x * 2 } |
| chained comparison | 0 < x && x < 10 | same as JS | same as JS |
| walrus | none | none | close to if n := len(a); n > 3 |
The full slice syntax is a[start:stop:step]; any part left empty takes its default (start, end, step 1). A Python slice creates a new list.
for ... else: the else block runs when the loop finishes without hitting break. Use it for "not found". Example: find the first even number in nums:
nums = [3, 7, 9]
for n in nums:
if n % 2 == 0:
print("first even number:", n)
break
else:
print("no even number")
# prints: no even number
All three numbers are odd, so the loop runs to the end without break and the else block runs. With nums = [3, 8, 9] it prints first even number: 8 and skips else.
match ... case (3.10) matches on the shape of the data, not only on a value like switch. Here event is a dict describing an order event:
event = {"type": "order", "id": 42, "total": 150_000}
match event:
case {"type": "order", "id": order_id}:
print("handle order", order_id)
case {"type": "refund"}:
print("refund")
case _:
print("unknown event")
# prints: handle order 42
case {"type": "order", "id": order_id}: matches wheneventhas a"type"key equal to"order"and has an"id"key. The value of"id"is bound to a new variableorder_id(here42). Extra keys such as"total"do not stop the match.case _:_matches anything, likedefaultin aswitch.150_000: the_in a number is only for readability; it equals150000.
The standard library you use daily
The standard library ships with Python: no pip install, only import. The table is a map; a runnable example of each module follows it.
| Module | Use it for |
|---|---|
collections | counting, grouping, queues |
datetime, zoneinfo | time with a time zone |
json | converting between JSON strings and dicts, lists |
pathlib | joining and splitting file paths |
logging | leveled logs instead of print |
re | pattern search (regex) |
enum | named constants |
Counting and grouping: Counter, defaultdict
Counter counts how many times each item appears:
from collections import Counter
c = Counter("banana")
print(c)
# prints: Counter({'a': 3, 'n': 2, 'b': 1})
print(c.most_common(2))
# prints: [('a', 3), ('n', 2)]
print(c["z"])
# prints: 0
A missing key returns 0 instead of raising.
defaultdict(list) is a dict that creates [] for a missing key, so grouping needs no if key not in d check. Example: group order ids by status:
from collections import defaultdict
orders = [("paid", 42), ("refunded", 7), ("paid", 43)]
g = defaultdict(list)
for status, order_id in orders:
g[status].append(order_id)
print(g["paid"])
# prints: [42, 43]
print(g["refunded"])
# prints: [7]
With a plain dict, the first g["paid"].append(42) raises KeyError because "paid" is not there yet.
Queues: deque
deque adds and removes at both ends in O(1) (removing from the front of a list is O(n)). maxlen keeps at most N items and pushes the oldest out when a new one arrives: a sliding window such as "the last 100 requests".
from collections import deque
q = deque(maxlen=3)
for x in [1, 2, 3, 4]:
q.append(x)
print(q)
# prints: deque([2, 3, 4], maxlen=3)
print(q.popleft())
# prints: 2
Time: datetime, zoneinfo
from datetime import datetime, timezone
from zoneinfo import ZoneInfo
t = datetime(2026, 12, 5, 2, 30, tzinfo=timezone.utc)
print(t.isoformat())
# prints: 2026-12-05T02:30:00+00:00
print(t.astimezone(ZoneInfo("Asia/Ho_Chi_Minh")).strftime("%H:%M %d/%m/%Y"))
# prints: 09:30 05/12/2026
tzinfo=timezone.utc: attaches the UTC zone. The current time with a zone isdatetime.now(timezone.utc).astimezone(...): the same instant in another zone (2:30 UTC = 9:30 in Vietnam).strftime: formats to a string;%H:%Mis hour:minute,%d/%m/%Yis day/month/year.
JSON
loads reads a JSON string into dicts and lists; dumps goes the other way. The trailing s stands for string.
import json
print(json.loads('{"id": 42, "paid": true}'))
# prints: {'id': 42, 'paid': True}
print(json.dumps({"id": 42, "paid": True}))
# prints: {"id": 42, "paid": true}
JSON true becomes Python True and back; null becomes None.
Paths: pathlib
from pathlib import Path
p = Path("data") / "orders.json"
print(p)
# prints: data/orders.json
print(p.name)
# prints: orders.json
print(p.suffix)
# prints: .json
print(p.parent)
# prints: data
The / operator joins paths with the right separator for the OS (/ on Linux and macOS, \ on Windows). To read a file: p.read_text(encoding="utf-8").
Logs: logging
import logging
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s: %(message)s")
log = logging.getLogger("orbit")
log.info("order %s paid", 42)
# prints: INFO orbit: order 42 paid
log.debug("hidden: below INFO")
# prints nothing: debug is below INFO
basicConfig: configure once at app start-up: the lowest level printed (INFO) and the line format.getLogger("orbit"): a logger by name. In real code writegetLogger(__name__), so the logger is named after the module and each line shows which file it came from.log.info("order %s ...", 42): pass values as arguments instead of an f-string; the string is only built if the line is actually printed.
Regex: re
import re
print(re.search(r"\d+", "order 1023 from Orbit").group())
# prints: 1023
print(re.findall(r"\d+", "orders 1023, 1024"))
# prints: ['1023', '1024']
print(re.match(r"\d+", "order 1023"))
# prints: None
r"\d+": thermakes a raw string, which keeps\as is instead of treating it as an escape;\d+means "one or more digits".searchfinds the first match anywhere and returns a match object;.group()gives the matched text.findallreturns a list of every match.matchonly matches at the start of the string:"order 1023"starts with a letter, so it returnsNone. A common mistake.
Named constants: enum
from enum import StrEnum
class Status(StrEnum):
PAID = "paid"
REFUNDED = "refunded"
print(Status.PAID == "paid")
# prints: True
print(repr(Status("refunded")))
# prints: <Status.REFUNDED: 'refunded'>
StrEnum (3.11) is an enum whose members are also strings, so they compare equal to "paid" and are written as "paid" to JSON or a database. Status("refunded") turns a string from a request into the enum; an unknown value raises ValueError.
Key takeaways
- Loop with
for x in ...; useenumeratefor the position andzipto pair two sequences. - Slicing
a[1:3]takes positions 1 up to, not including, 3; a comprehension filters and transforms in one line. - The standard library ships with Python, just
import:Countercounts,jsonconverts to and from dicts,pathlibjoins paths.
Sources
- The Python Standard Library (opens in a new tab):
collections,datetime,json,pathlib,logging,re,enum. - match statement (PEP 636) (opens in a new tab).
- Every example with a
# printsline was run on Python 3.11.9.
