Working with DataCore· 35 min read

Lists

Store many items in order — the most-used Python data structure.

What you will learn

  • Create and read lists
  • Add and remove items
  • Loop and slice lists

A list of items

A list holds many values in order, inside square brackets [ ] and separated by commas. Each item has a position number called an index, and counting starts at 0 — so the first item is at index 0, not 1.

Lists are ordered and start at index 0
colors = ["red", "green", "blue"]
print(colors[0])     # red  (first item — index starts at 0)
print(len(colors))   # 3
colors.append("yellow")   # add to the end
print(colors)

Line by line: we make a list of three colours. colors[0] reaches in at index 0 and gives the first item, red. len(colors) counts how many items there are — 3. colors.append("yellow") adds a new item onto the end of the list. The final print(colors) shows the whole list, now with four colours including the one we just added.

Note: Output: red 3 ['red', 'green', 'blue', 'yellow']

Here are the everyday list actions you will reach for most often:

ActionCode
Add to endlist.append(x)
Remove an itemlist.remove(x)
Lengthlen(list)
Slice (first 2)list[0:2]
Last itemlist[-1]

Watch out: Indexes start at 0, so the first item is list[0] and the last is list[-1].

Q. How do you add an item to the end of a list?

Answer: append() adds an item to the end of a Python list.

✍️ Practice

  1. Make a list of 5 subjects and print the first and last.
  2. Add and remove an item, then print the list.

🏠 Homework

  1. Build a to-do list: start empty, append three tasks, print them with a loop.
Want to learn this with a mentor?

CodingClave runs guided, project-based training (28-day, 45-day & 6-month batches).

Explore Training →