Skip to content
Visual explainer 8h to learn 6 steps

Python core: types, control flow, data structures

Write idiomatic Python with lists, dicts, comprehensions and functions.

By Invicly Tech, , in Full DevOps with Python. About 12 minutes to read.

Topic 5 of 34

In short

Python's built-in types and data structures cover most automation work. Knowing when to use a list, dict or set, and writing small functions, turns long shell scripts into readable tools.

Explained simply

Python is a programming language that reads almost like English. For DevOps work you mostly use a small part of it: text (strings), numbers, true or false values (booleans), and a few ways to group data. With just those pieces you can replace long, fragile shell scripts with code that is easy to read and test.

Data comes in collections. A list is an ordered row of items, like server names. A dict (dictionary) maps a key to a value, like a server name to its IP address. A set holds unique items and answers "is this in here?" very quickly. A tuple is a small fixed group, like (host, port).

Control flow decides what runs. if picks a path, for repeats work for each item, and while repeats until something changes. A function wraps steps under a name, so you write the logic once and call it many times with different inputs.

A comprehension is a short way to build a new list or dict from an old one in one line, for example [name.upper() for name in names]. It replaces three or four lines of loop code. Used with care, it makes scripts shorter and clearer, not cleverer.

Press Play on a diagram to walk through it one step at a time.

MapBuilt-in collections
Python collections
  • list [ ]
    • Ordered, changeable
    • Duplicates allowed
    • Server names to loop over
  • dict { k: v }
    • Key to value lookup
    • Fast access by key
    • Config or JSON data
  • set { }
    • Unique items only
    • Fast membership test
    • Find missing hosts
  • tuple ( )
    • Ordered, unchangeable
    • Fixed records
    • Return multiple values
FlowHow f(1, 2, 3, force=True, tag="x") binds to def f(a, *args, force=False, **kw)
  1. Step 1
    a = 1

    First positional value fills a

  2. Step 2
    args = (2, 3)

    Extra positional values become a tuple

  3. Step 3
    force = True

    Keyword-only, matched by name

  4. Step 4
    kw = {"tag": "x"}

    Unknown keywords become a dict

CompareThree ways to process many items
for loop
  • Any logic, try/except, logging
  • Easiest to debug
  • Use when it grows past one filter
List comprehension
  • Builds the whole list at once
  • One loop plus one filter
  • Short and fast
Generator expression
  • One item at a time
  • Tiny memory use
  • Feed it to sum, any, max or join

In depth

Names, objects and the mutable default trap

In Python a variable is a name tag stuck on an object, not a box that holds a copy. After b = a, both names point to the same list, so b.append(1) also changes a. Strings, numbers and tuples are immutable (they cannot change), so sharing them is safe. Lists, dicts and sets are mutable, so sharing them can surprise you.

To get a separate list, copy it: a.copy() or list(a). That is a shallow copy: the outer list is new, but nested lists inside are still shared. For nested data use copy.deepcopy(a).

Default argument values are created once, when def runs, not on every call. So def add(x, items=[]) keeps one list that grows across calls. The fix is items=None, then items = [] inside the function.

  • b = a shares one object; b = a.copy() makes a new one
  • Shallow copy: new outer container, shared inner items
  • Use None as the default for list and dict parameters
CompareImmutable vs mutable
Immutable
  • str, int, float, bool, tuple
  • A change makes a new object
  • Safe to share between names
  • Can be dict keys and set items
Mutable
  • list, dict, set
  • Changed in place
  • Every name sees the change
  • Cannot be dict keys or set items

Why dict and set lookups are fast

A list checks membership by looking at each item in turn, so host in big_list gets slower as the list grows. This is O(n): time grows with the number of items. A dict or set stores items in a hash table. Python runs hash() on the key, which turns it into a number, and that number points almost directly to the right slot. On average a lookup takes about the same time for ten items or ten million (O(1)).

This is why keys must be hashable: their value must never change. Strings, numbers and tuples of those work as keys. Lists and dicts do not, and Python raises TypeError: unhashable type.

Since Python 3.7, dicts keep insertion order, so looping over a dict gives keys in the order you added them. Sets have no guaranteed order, so sort them before printing.

FlowWhat d[key] does
  1. Step 1
    hash(key)

    Turn the key into a number

  2. Step 2
    Pick a slot

    The number points into the table

  3. Step 3
    Compare keys

    Check the stored key equals yours

  4. Step 4
    Return value

    Or raise KeyError if no match

Truthiness, None and comparisons

In an if, Python treats some values as false: False, None, 0, 0.0, the empty string, and empty collections like [], {} and set(). Everything else is true. So if hosts: means "if the list is not empty", which is the normal way to write it.

== compares values, while is checks whether two names point to the very same object. Use is only for None (if x is None), because two equal strings or numbers may or may not be the same object.

Comparisons can be chained: 0 <= cpu < 80 reads like maths and works. and and or stop early (short-circuit) and return one of their operands, so name = given or "default" picks the first truthy value. Be careful: it also replaces 0 and the empty string, which may be valid inputs.

  • Falsy: False, None, 0, 0.0, "", [], {}, set()
  • Write x is None, not x == None
  • port = cfg.get("port") or 8080 also replaces a real port 0

Comprehensions, generators and when to stop

A list comprehension builds the whole list in memory at once. A generator expression uses round brackets instead, (x for x in items), and produces one item at a time when asked. Passing a generator to sum(), any(), max() or "".join() lets you process a huge file without holding it all in memory: sum(1 for line in f if "ERROR" in line).

Dict and set comprehensions use curly brackets: {h: ip for h, ip in pairs} and {line.split()[0] for line in lines}.

A comprehension is great for one loop with one filter. Once you need two nested loops plus conditions, or a try/except, a normal for loop is easier to read and debug. Readable beats short. Also avoid comprehensions used only for side effects, like [print(x) for x in items]; that builds a list nobody uses.

Function arguments in full

Python matches arguments to parameters in a fixed order. Positional arguments fill the named parameters left to right. Extra positional values go into *args as a tuple. Parameters after *args (or after a bare *) are keyword-only: callers must write their name, which prevents unclear calls like deploy("web", True, False). Extra keyword arguments go into **kwargs as a dict.

The same stars work in reverse at the call site: f(*hosts) spreads a list into positional arguments, and f(**opts) spreads a dict into keyword arguments. This is common when passing settings through to another function.

A function returns None unless you return something. Returning several values (return ok, msg) really returns one tuple, which the caller can unpack: ok, msg = check(host).

  • def f(a, b=2, *args, force=False, **kwargs)
  • def deploy(env, *, dry_run=False) forces callers to write dry_run=True
  • ok, msg = check(host) unpacks a returned tuple

Learn it in 6 short steps

About 1h 20m each. Track them with a timer in your plan.

  1. 1
    Practice strings, numbers and booleans~1h 20m
  2. 2
    Use lists, dicts, sets and tuples~1h 20m
  3. 3
    Write loops, conditionals and functions~1h 20m
  4. 4
    Rewrite loops as comprehensions~1h 20m
  5. 5
    Use *args, **kwargs and default arguments~1h 20m
  6. 6
    Solve 10 small automation exercises~1h 20m

Key points

  • Pick the structure by the question: order matters, look up by key, or uniqueness.
  • Comprehensions build lists and dicts in one readable line from existing data.
  • Small functions with clear names and default arguments make scripts reusable.
  • *args and **kwargs collect extra positional and keyword arguments.

Key terms

Tap a card to flip it. 0/4 known

Examples

python
servers = [
    {"name": "web1", "cpu": 82, "env": "prod"},
    {"name": "web2", "cpu": 35, "env": "prod"},
    {"name": "dev1", "cpu": 91, "env": "dev"},
]

def busy(items, limit=80, env=None):
    return [s["name"] for s in items
            if s["cpu"] > limit and (env is None or s["env"] == env)]

print(busy(servers))              # ['web1', 'dev1']
print(busy(servers, env="prod"))  # ['web1']
by_name = {s["name"]: s["cpu"] for s in servers}
print(by_name.get("web3", "unknown"))

Lists of dicts, a comprehension and default arguments.

Count HTTP status codes in an access log

You want to know how many 5xx errors nginx served today. Step 1: open the log with a with block and loop over it line by line, so even a huge file uses little memory. Step 2: split each line on whitespace; in the default combined log format the status code is field 8 (counting from 0). Step 3: count with collections.Counter, which is a dict built for counting. Step 4: print the most common codes and add up everything starting with 5.

python
from collections import Counter

counts = Counter()
with open("access.log", encoding="utf-8") as f:
    for line in f:
        parts = line.split()
        if len(parts) > 8 and parts[8].isdigit():
            counts[parts[8]] += 1

for status, n in counts.most_common(5):
    print(f"{status}: {n}")
errors = sum(n for s, n in counts.items() if s.startswith("5"))
print("5xx total:", errors)

Compare expected and running hosts with sets

Your inventory lists the hosts that should exist, and monitoring reports the hosts that are actually up. Step 1: put both into sets. Step 2: expected minus running gives hosts that are missing. Step 3: running minus expected gives surprise hosts, such as a forgotten test machine still costing money. Step 4: the intersection gives the healthy ones. Sorting before printing makes the output stable, because sets have no order.

python
expected = {"web1", "web2", "web3", "db1"}
running = {"web1", "web3", "db1", "tmp-test"}

missing = expected - running        # {'web2'}
unexpected = running - expected     # {'tmp-test'}
healthy = expected & running

print("Missing:", sorted(missing))
print("Unexpected:", sorted(unexpected))
print(f"{len(healthy)}/{len(expected)} expected hosts are up")

Quick reference

  • d.get(key, default) avoids KeyError when a key may be missing
  • for i, item in enumerate(items, start=1) gives a counter without range(len(items))
  • for host, ip in zip(hosts, ips) walks two lists side by side
  • sorted(servers, key=lambda s: s["cpu"], reverse=True) sorts dicts by one field
  • collections.Counter(words).most_common(3) counts and ranks in one line
  • Sets: a - b is difference, a & b intersection, a | b union
  • f"{value:.1f}%" rounds to one decimal; f"{name:<10}" pads to a column
  • Use def f(x, items=None) instead of items=[] to avoid a shared default list

Common mistakes

  • Using a mutable default like def f(x=[]); the same list is shared between calls.
  • Indexing a dict with d[key] when the key may be missing; use d.get(key).

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1After a = [1, 2]; b = a; b.append(3), what is a?

Question 2

2Which of these can be used as a dict key?

Question 3

3What does def f(*, dry_run=False) mean for callers?

Question 4

4Why is host in hosts_set faster than host in hosts_list for 100,000 hosts?

Question 5

5What is the value of port after port = 0 or 8080?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Given a list of dicts with name and env keys, print the names of the prod servers in alphabetical order using one comprehension.

  2. Exercise 2medium

    Write parse_kv(text) that turns lines like key=value into a dict. Skip blank lines and lines starting with #, and strip spaces around keys and values.

  3. Exercise 3hard

    Write group_by(items, key) that returns a dict of lists grouped by one field. Use it to count servers per env and to find the env with the most busy servers (cpu over 80).

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Should I learn Python 2 or Python 3?
Python 3 only. Python 2 reached end of life on 1 January 2020 and receives no fixes, and every current tool expects Python 3.
What is the difference between a list and a tuple?
A list can change after you create it; a tuple cannot. Use tuples for small fixed records like (host, port) and lists for collections that grow or shrink.
When should I use a class instead of a dict?
When the same shape of data appears all over your code. A dataclass gives named fields, type hints and a readable repr, and typos become errors instead of silent new keys.
Is Python fast enough for DevOps scripts?
Yes. Automation scripts spend most of their time waiting for disks, networks and other programs, so Python's speed is rarely the bottleneck.

Go deeper

ShareXLinkedInWhatsApp