Skip to content
Fullstack Launchpad

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.

By Published Updated 8 min readPython for Engineers Switching Languages

Loops, everyday syntax and the standard library

What does the code below print?

python
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.

SectionExampleResult
Loopsenumerate(courses)0 Redis, 1 Python, 2 Redis
Everyday syntax[n.lower() for n in courses if n != "Python"]['redis', 'redis']
Standard libraryCounter(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.

WriteMeaningResult
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 step0 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, continueleave the loop; skip the rest of this pass
python
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 -= 1 is n = n - 1.
  • list(range(...)) is only there to print the numbers; range itself 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.

WriteMeaningResult
a[-1]last item50
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 = aunpackingfirst = 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 * 2one-expression anonymous functiona function; called with 5 it returns 10
0 < x < 10chained comparisonTrue
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.

JobJSJavaGo
last itema.at(-1)a.get(a.size() - 1)a[len(a)-1]
slicinga.slice(1, 3)a.subList(1, 3)a[1:3]
reversed[...a].reverse()Collections.reversewrite a loop
unpackingconst [first, ...rest] = anonenone
merge dicts{...d1, b: 2}putAllcopy in a loop
list comprehensionfilter().map()stream().filter().map()a loop
lambdax => x * 2x -> x * 2func(x int) int { return x * 2 }
chained comparison0 < x && x < 10same as JSsame as JS
walrusnonenoneclose 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:

python
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:

python
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 when event has a "type" key equal to "order" and has an "id" key. The value of "id" is bound to a new variable order_id (here 42). Extra keys such as "total" do not stop the match.
  • case _: _ matches anything, like default in a switch.
  • 150_000: the _ in a number is only for readability; it equals 150000.

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.

ModuleUse it for
collectionscounting, grouping, queues
datetime, zoneinfotime with a time zone
jsonconverting between JSON strings and dicts, lists
pathlibjoining and splitting file paths
loggingleveled logs instead of print
repattern search (regex)
enumnamed constants

Counting and grouping: Counter, defaultdict

Counter counts how many times each item appears:

python
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:

python
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".

python
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

python
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 is datetime.now(timezone.utc).
  • astimezone(...): the same instant in another zone (2:30 UTC = 9:30 in Vietnam).
  • strftime: formats to a string; %H:%M is hour:minute, %d/%m/%Y is day/month/year.

JSON

loads reads a JSON string into dicts and lists; dumps goes the other way. The trailing s stands for string.

python
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

python
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

python
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 write getLogger(__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

python
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+": the r makes a raw string, which keeps \ as is instead of treating it as an escape; \d+ means "one or more digits".
  • search finds the first match anywhere and returns a match object; .group() gives the matched text.
  • findall returns a list of every match.
  • match only matches at the start of the string: "order 1023" starts with a letter, so it returns None. A common mistake.

Named constants: enum

python
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 ...; use enumerate for the position and zip to 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: Counter counts, json converts to and from dicts, pathlib joins paths.

Sources