PYTHON · PYTHON FOR EVERYONE · CHAPTER 4

Collections

Group data in lists, tuples and dictionaries, and navigate an inventory or a JSON response with ease.

7 min readCourse: Python for EveryoneLevel: beginner

From point A to point B

Point A: you can handle numbers, strings and booleans, but each variable holds a single value. A network inventory has dozens of devices, each with its own interfaces and properties. Point B: by the end of this chapter, you'll group data in lists, tuples and dictionaries, access any element by position or by key, extract pieces with slicing and navigate a JSON response from an API.

Lists: create, read and modify

A list is an ordered collection of elements. It's what other languages call an array or a vector. You write it inside square brackets, with the elements separated by commas.

A list can hold any type of data, mixed together: numbers, strings, booleans and even other lists.

interfaces = ["Gi0/0", "Gi0/1", "Gi0/2", "Gi0/3", "Lo0"]
mixed = [48, True, "R1-Lima", [10, 20]]
print(len(interfaces))   # → 5
print(interfaces[0])     # → Gi0/0
print(interfaces[4])     # → Lo0
print(mixed[3][1])       # → 20

You access an element by writing its index inside square brackets. The first element has index 0, not 1. That's why, in a 5-element list, the last one is number 4. The len() function tells you how many elements there are.

If an element is itself a list, you chain brackets. mixed[3] is the list [10, 20], and mixed[3][1] is its second element, 20.

Lists are mutable: you can change an element by assigning it a new value. Asking for an index that doesn't exist raises an IndexError.

interfaces = ["Gi0/0", "Gi0/1", "Gi0/2", "Gi0/3", "Lo0"]
interfaces[4] = "Loopback0"
print(interfaces)   # → ['Gi0/0', 'Gi0/1', 'Gi0/2', 'Gi0/3', 'Loopback0']
try:
    interfaces[5]
except IndexError as error:
    print("IndexError:", error)   # → IndexError: list index out of range

Negative indexes

Python lets you count from the end with negative indexes. [-1] is the last element, [-2] the one before it, and so on. You don't need to know how many elements the list has.

interfaces = ["Gi0/0", "Gi0/1", "Gi0/2", "Gi0/3", "Loopback0"]
print(interfaces[-1])    # → Loopback0
print(interfaces[-2])    # → Gi0/3

It's very handy for grabbing the last line of a log or the last hop of a traceroute.

Slicing: pieces of a sequence

Slicing extends the square brackets to extract a piece of the list. With [start:stop], you get the elements from start up to stop, not including the latter. With a third number, [start:stop:step], you skip ahead by that many at a time.

vlans = [10, 20, 30, 40, 50, 60]
print(vlans[0:2])     # → [10, 20]
print(vlans[1:4])     # → [20, 30, 40]
print(vlans[0:6:2])   # → [10, 30, 50]

You can leave out the start or the stop. Without a start, it begins at the beginning; without a stop, it goes all the way to the end. You can also use negative numbers, with the same meaning as in indexes.

vlans = [10, 20, 30, 40, 50, 60]
print(vlans[2:])      # → [30, 40, 50, 60]
print(vlans[:3])      # → [10, 20, 30]
print(vlans[-2:])     # → [50, 60]
print(vlans[::2])     # → [10, 30, 50]
print(vlans[::-1])    # → [60, 50, 40, 30, 20, 10]
print(vlans[4:100])   # → [50, 60]
copy = vlans[:]
print(copy == vlans, copy is vlans)  # → True False

3 useful details. A negative step walks the list backward. An out-of-range slice doesn't raise an error: it returns whatever exists. And [:] creates a new copy of the list, with the same content but independent.

Modify lists with slicing

Slicing also works on the left side of an assignment. That way, you replace a whole stretch of the list. If the new list has a different size, the original list grows or shrinks.

vlans = [10, 20, 30, 40]
vlans[0:2] = [100, 200]
print(vlans)          # → [100, 200, 30, 40]
vlans[0:2] = [999]
print(vlans)          # → [999, 30, 40]
vlans[1:1] = [15, 25]
print(vlans)          # → [999, 15, 25, 30, 40]
vlans[:] = []
print(vlans)          # → []

An empty stretch like [1:1] inserts elements without deleting any. Still, for everyday work, lists have more readable methods, such as append(), insert() or remove(). You'll see them when you study classes and objects.

Tuples

A tuple looks a lot like a list: it's ordered and supports indexes and slicing. You write it with parentheses instead of square brackets. The big difference is that it's immutable: once created, you can't change, add or remove elements.

mgmt = ("10.0.0.1", 22, "ssh")
print(type(mgmt))         # → <class 'tuple'>
print(mgmt[0])            # → 10.0.0.1
print(mgmt[0:2])          # → ('10.0.0.1', 22)
try:
    mgmt[1] = 2222
except TypeError as error:
    print("TypeError:", error)  # → TypeError: 'tuple' object does not support item assignment

What actually creates a tuple is the comma, not the parentheses. Parentheses are only required for the empty tuple or when there's ambiguity. Even so, use them for clarity. The practical consequence shows up with a single element: you need a trailing comma.

point = 10, 20
print(type(point), point)   # → <class 'tuple'> (10, 20)
single = (1)
print(type(single))         # → <class 'int'>
single = (1,)
print(type(single))         # → <class 'tuple'>
ip, port, protocol = ("10.0.0.1", 22, "ssh")
print(port)                 # → 22

Without the comma, (1) is just the number 1 in parentheses. The last assignment shows unpacking: you spread the tuple's elements across several variables at once.

When should you use a tuple? When the data forms a fixed record that shouldn't change, like a service's (IP, port) pair. A list has 11 methods to modify it; a tuple has only 2, count() and index(). In exchange, a tuple uses a bit less memory and, as you'll see shortly, can be used as a dictionary key.

Strings are sequences too

Lists and tuples belong to a family of types called sequences: ordered collections you access by position. Text strings are sequences too, so they support indexes and slicing.

interface = "GigabitEthernet0/1"
print(interface[0])      # → G
print(interface[-3:])    # → 0/1
print(interface[:7])     # → Gigabit
print(len(interface))    # → 18
try:
    interface[0] = "g"
except TypeError as error:
    print("TypeError:", error)  # → TypeError: 'str' object does not support item assignment

Like tuples, strings are immutable. To “change” a string, you create a new one from the old one.

Dictionaries

A dictionary maps keys to values. Other languages call it an associative array, a map or a hash. You write it inside curly braces, with key: value pairs separated by commas. It's the natural structure for describing a device.

router = {
    "hostname": "R1-Lima",
    "mgmt_ip": "10.0.0.1",
    "role": "edge",
    "ports": 4,
}
print(router["hostname"])          # → R1-Lima
router["role"] = "core"            # reassign a value
router["site"] = "Lima"            # add a new key
print(len(router))                 # → 5
print("site" in router)            # → True
print("vlan" in router)            # → False
print(router.get("vlan"))          # → None
print(router.get("vlan", 1))       # → 1

You access a value by its key, not by position, with the same square brackets. Assigning to an existing key changes its value; assigning to a new key adds it. If you ask for a key that doesn't exist with square brackets, you get a KeyError. To avoid it, check first with in or use get(), which returns None or the default value you give it.

What can be a key

Keys must be hashable, which in practice means immutable: numbers, strings, booleans or tuples of immutable values. Lists and dictionaries can't be keys.

neighbors = {
    ("R1", "Gi0/0"): "R2",
    ("R1", "Gi0/1"): "SW1",
}
print(neighbors[("R1", "Gi0/1")])  # → SW1
try:
    bad = {["R1", "Gi0/0"]: "R2"}
except TypeError as error:
    print("TypeError:", error)     # → TypeError: cannot use 'list' as a dict key (unhashable type: 'list')

Why this rule? A dictionary is a hash table. When it stores a pair, Python computes a number (the hash) from the key and uses it to find the key instantly later. If the key could change, its hash would change and the value would be lost.

Dictionary order and views

Dictionaries keep insertion order: when you loop over them, the keys come out in the order you added them. The keys(), values() and items() methods return views that reflect the dictionary at all times.

inventory = {"R1": "10.0.0.1", "R2": "10.0.0.2", "SW1": "10.0.0.10"}
print(list(inventory))             # → ['R1', 'R2', 'SW1']
keys = inventory.keys()
print(keys)                        # → dict_keys(['R1', 'R2', 'SW1'])
inventory["SW2"] = "10.0.0.11"
print(keys)                        # → dict_keys(['R1', 'R2', 'SW1', 'SW2'])
print(inventory.items())
['R1', 'R2', 'SW1']
dict_keys(['R1', 'R2', 'SW1'])
dict_keys(['R1', 'R2', 'SW1', 'SW2'])
dict_items([('R1', '10.0.0.1'), ('R2', '10.0.0.2'), ('SW1', '10.0.0.10'), ('SW2', '10.0.0.11')])

Notice that keys updated itself when you added SW2: it's a view, not a copy. Even though they're ordered, dictionaries aren't sequences but mappings. That's why they don't support slicing: inventory[0:2] doesn't give you the first 2 pairs; it raises a KeyError, because Python looks for a key equal to that slice.

Python 3.14 update. The original book said dictionaries have no order. Since Python 3.7, the language guarantees insertion order. Also, in Python 3, keys(), values() and items() return views instead of lists, and the has_key() method no longer exists: use key in dictionary.

Nested collections: a JSON response

Collections combine: lists of dictionaries, dictionaries with lists inside, and so on to any depth. That's exactly the shape of JSON responses from network APIs. The json module turns them into Python dictionaries and lists.

import json

response = """{
  "hostname": "R1-Lima",
  "interfaces": [
    {"name": "Gi0/0", "vlan": 10},
    {"name": "Gi0/1", "vlan": 20}
  ],
  "location": ["Lima", "Floor 3"]
}"""
data = json.loads(response)
print(type(data))                        # → <class 'dict'>
print(data["interfaces"][1]["name"])     # → Gi0/1
print(data["interfaces"][-1]["vlan"])    # → 20
print(data["location"][0])               # → Lima

Read data["interfaces"][1]["name"] from left to right: from the main dictionary, you take the interfaces key, which is a list. From that list, you take element 1, which is a dictionary. And from that dictionary, the name key. With this technique, you'll pull any piece of data out of an API.

Challenge

Answer before you open the solution.

1. If v = [10, 20, 30, 40, 50], what does v[1:4] return?

[20, 30, 40]. Slicing includes the start index and excludes the stop index.

2. What's the type of ("R1")? And of ("R1",)?

str and tuple. The comma is what creates the tuple. Without it, the parentheses only group.

3. Can you use ["R1", "Gi0/0"] as a dictionary key? What would you use instead?

No; use the tuple ("R1", "Gi0/0"). Lists are mutable and aren't hashable. Tuples of immutable values are.

4. How do you check whether the router dictionary has the "site" key in Python 3?

With "site" in router. Python 2's has_key() method no longer exists.

5. How do you get the last element of a list without knowing its length?

With index -1. Negative indexes count from the end: my_list[-1] is the last one.

Key takeaways

  • Lists [] are ordered and mutable; indexes start at 0 and accept negative values.
  • Slicing [start:stop:step] extracts pieces, excludes the stop and also replaces stretches.
  • Tuples () are immutable; the comma creates them, so (1,) is a tuple and (1) isn't.
  • Strings are immutable sequences too: they support indexes and slicing.
  • Dictionaries {} map hashable keys to values and keep insertion order.
  • A JSON response is a nest of dictionaries and lists that you walk by chaining square brackets.

In chapter 5, you'll make decisions and repeat tasks with control flow: if, for and while.

Official resources

Source and credits. This course is based on the book Python para todos by Raúl González Duque, published under the Creative Commons Attribution 2.5 Spain license. The original book was written for Python 2.5. Jesús Espinoza, with AI assistance, brought it to Python 3.14: he rewrote every chapter in his own words, replaced the examples with networking cases, updated the syntax and the modules that no longer exist, fixed errors in the original and tested all the code with Python 3.14.6 against the official documentation.

Navigate