Brainlag
  1. Library
  2. Concepts
  3. Python

Lists and positions

A Python list keeps values in order. Read items by position, count from the end with negative indexes, take slices and change the list in place.

Python8 min

Positions start at zero

A list keeps its items in order, and every item has a position called an index. The first item is at index 0, not 1. Python also counts backwards: index -1 is the last item, -2 the one before it.

Positions in a list

squad holds "Ana", "Ben", "Cleo", "Dev", "Eli".

So for squad = ["Ana", "Ben", "Cleo", "Dev", "Eli"], both squad[2] and squad[-3] are "Cleo". len(squad) is 5, which means the last valid index is 4. Asking for squad[5] is an IndexError.

A slice takes a run of items: squad[0:3] is the first three. The start is included, the end is not.

Changing a list in place

Lists can change after you make them. append adds to the end, remove takes out the first matching value, and assigning to an index replaces one item.

Step through it
squad = ["Ana", "Ben"]
squad.append("Cleo")
squad[0] = "Dev"
squad.remove("Ben")
size = len(squad)

These methods change the list itself and give back None, so write squad.append("Cleo"), never squad = squad.append("Cleo").

Run it: a race result

Run it, then change one thing and run it again.

main.py to run
finishers = ["Mo", "Priya", "Jack", "Lena", "Sam"]
print("Winner:", finishers[0])
print("Last:", finishers[-1])
print("Podium:", finishers[:3])

finishers.append("Zoe")
print(len(finishers), "runners finished")

Print the podium

Print the winner, then the runner who came last, then a list of the top three. Read every name from finishers, so the code still works if the race result changes.

Constraint

  • Use a negative index for the last runner.
  • Read the names from the list instead of typing them.
exercise_1.py to run
finishers = ["Mo", "Priya", "Jack", "Lena", "Sam", "Zoe"]
# print the winner, the last runner, then the top three

Code editor. Press Control or Command plus Enter to run the code. Tab indents; to move focus out of the editor, press Escape and then Tab.