Raw data, clear context.

[
[
[

]
]
]

Your shopping list has four items. You want to print the first one, then pull out the two in the middle. A Python list keeps the items together, and a slice gives you a new list containing the items you pick.[1]

Write the items between square brackets, with a comma between each pair.[1] To read one item, put its index (its position in the list) in brackets after the list name. Python counts from zero, so shopping[0] reads the first item.[2] Negative indices count back from the end: shopping[-1] reads the last item.[2]

Save this as shopping.py.

shopping.py
Python
shopping = ["oats", "milk", "pears", "tea"]
print(shopping[0])
print(shopping[-1])
print(shopping[1:3])
print(shopping[:2])
print(shopping[1:8])

Run the command in the folder where you saved the file. The example was tested with Python 3.14.9 on Linux.

Run shopping.py
Bash
python3 shopping.py
Output
Plain text
oats
tea
['milk', 'pears']
['oats', 'milk']
['milk', 'pears', 'tea']
Shopping list by index: 0 oats, 1 milk, 2 pears, 3 tea. For shopping[1:3], milk and pears are shaded as included. Tea is at index 3, where the slice stops.
The slice starts at index 1 and stops before index 3. The shaded items are the two values returned in the new list.

Which items make it into a slice?

Read shopping[1:3] as “start at index 1 and stop before index 3”. The start is included; the stop is excluded.[2] Here that gives you milk and pears. Tea sits at index 3, just outside the slice.

You can leave either end blank. In shopping[:2], Python starts at index 0. With an omitted stop, the slice runs to the end of the list.[2]

When the number is too large

If you changed the last line to print(shopping[8]), it would ask for one item at a position that does not exist. The run stops with IndexError.[3] In shopping[1:8], the stop is a boundary. Python brings it back to the end of the list, so the slice can still include milk, pears and tea.[2]

Your turn

Add one line that prints the last two items as a list. Start at index 2 and leave the stop blank. The result should contain pears followed by tea.

The next lesson uses tuples to group values and unpack them into separate variables.

Sources

  1. Python 3.14 tutorial: Lists
  2. Python 3.14 library reference: Common sequence operations
  3. Python 3.14 library reference: IndexError