LESSON · 1 OF 5

Creating and accessing lists

Creating and accessing lists

A list is an ordered collection of values kept in a single variable. Write one with square brackets and commas between the items:

python
servers = ["web-01", "web-02", "db-01"]

Lists keep their order, so the item you put first stays first. They can hold any type, and you can even mix types in one list, though in practice you'll usually keep a list to one kind of thing:

python
ports = [80, 443, 8080]
mixed = ["web-01", 8080, True]
empty = []

Reaching an item by index

Each item has a position, called its index, starting at 0. Use square brackets with the index to read one item:

python
servers = ["web-01", "web-02", "db-01"]
print(servers[0])   # web-01
print(servers[2])   # db-01

Counting from zero trips up everyone at first. The third item is at index 2, not 3.

Negative indexes count from the end, which saves you from working out the length just to grab the last item:

python
print(servers[-1])  # db-01
print(servers[-2])  # web-02

Slicing out a range

A slice pulls several items at once with start:stop. The start is included and the stop is not:

python
nums = [10, 20, 30, 40, 50]
print(nums[1:3])    # [20, 30]
print(nums[:2])     # [10, 20]
print(nums[2:])     # [30, 40, 50]

Leaving out the start means "from the beginning" and leaving out the stop means "to the end". A slice always hands back a new list.

Spin up a fresh environment and practice live.
python-devops · fresh machine · ready in under a minute