02 / COLLECTIONS AND DECISIONS · LESSON 06

Keep an ordered collection

Add to a list and select values by position.

11 min · learn at your pace

Several values, one name

A list holds values in order and can change after it is created. Square brackets create it: ["web-01", "db-01"]. append() adds one item at the end. It changes the list in place and returns None, so do not write hosts = hosts.append(...).

Indexes start at zero. hosts[0] is the first item, and hosts[-1] is the last. Asking for an index outside the list raises IndexError. A slice such as hosts[:2] returns a new list with the first two items; its stopping index is excluded.

Mutating and copying

Assigning one list to a second name does not copy its contents. Both names then refer to the same list. Use hosts.copy() or a slice when you need an independent shallow copy. Nested lists need additional care because their inner objects are still shared.

Use a list when order or repeated values matter. In an inventory export, the order might match source records, and duplicates may be evidence of a data problem. Removing duplicates too early can hide that problem. Later you will use sets for a different job: membership and uniqueness.

Try an example.py
hosts = ["web-01", "db-01"]
hosts.append("dns-01")
print(hosts[0], hosts[-1])
print(hosts[:2])
YOUR TURN

Put it into practice.

Start with hosts = ["srv-web", "srv-dns"]. Append "srv-db". Save first_host, last_host, and selected_hosts (the first two entries) without removing entries from hosts.

See an explained solution
One way to solve it.py
hosts = ["srv-web", "srv-dns"]
hosts.append("srv-db")
first_host = hosts[0]
last_host = hosts[-1]
selected_hosts = hosts[:2]
print(selected_hosts)

Appending preserves the original order. Indexing returns individual values; slicing returns a new list.