Python Fundamentals ยท Collections

Slicing Lists

Take parts of a list with [start:stop:step], reverse it, and copy it so changes do not leak back.

slicing.py

days = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"]
weekdays = days[:5]          # from the start up to index 5
weekend = days[5:]           # from index 5 to the end
every_other = days[::2]      # step 2
backwards = days[::-1]       # step -1 reverses
copy = days[:]               # a new list with the same items
copy[0] = "MON"
print(weekdays, weekend, every_other, backwards, days[0], copy[0])

Step by step

  1. days is created and points to a new list: ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'].
  2. Leave out the start to begin at 0: the first five days.
  3. Leave out the stop to go to the end.
  4. A step of 2 takes every other item.
  5. A step of -1 walks backwards: the list reversed.
  6. [:] slices everything: a new list with the same items.
  7. Only the copy changes; Memory shows two separate list objects.
  8. days[0] is still "mon" while copy[0] is "MON". Slices read parts and make copies.