Loops, and where your data lives

INPUT · Slides

Cutting out a part

01 / 07

When you want several

fruits[0] takes one. So what do you do when you want the first three?

You could write it out three times, but Python has a way to name a range and cut the lot out in one go. It is called a slice.

02 / 07

Write the range with a colon

Inside the square brackets you write start:end. So fruits[1:3] means from number 1 up to just before number 3.

What comes back is a list. Unlike taking one out, it arrives wrapped in [ ].

fruits = ["apple", "orange", "grape", "peach"]print(fruits[1:3])

Result

['orange', 'grape']

03 / 07

The end number is not included

The end of a slice is not "up to here" but "up to just before here". [1:3] holds 1 and 2, and not 3.

It looks unhelpful, but there is a payoff. Take the start from the end and you have how many you will get. 3 - 1 is two, with no recounting.

It is the same rule that made range(3) stop after 0, 1, 2. Python does not include the end — learn it once and be done.

numbers = [10, 20, 30, 40, 50]print(numbers[0:2])print(numbers[2:5])

Result

[10, 20]
[30, 40, 50]

04 / 07

Leave the start out

Leave out the start and write [:2] and it means from the front.

It is the same as [0:2], but without the 0 the intent, from the very beginning, comes across more plainly.

fruits = ["apple", "orange", "grape", "peach"]print(fruits[:2])

Result

['apple', 'orange']

05 / 07

Leave the end out

The other way round, leave out the end and write [2:] and it means from there to the end.

You reach the end without knowing how many there are, so there is no need to call len. Python being kind again.

fruits = ["apple", "orange", "grape", "peach"]print(fruits[2:])print(fruits[-2:])

Result

['grape', 'peach']
['grape', 'peach']

06 / 07

Cut the whole thing out and you have a copy

Leave both out, [:], and you get the whole thing. The same contents come straight back.

That sounds pointless, but it is how you make a copy. What comes back is a separate list, so append to one and the other does not move.

fruits = ["apple", "orange"]copy = fruits[:]copy.append("grape")print(fruits)print(copy)

Result

['apple', 'orange']
['apple', 'orange', 'grape']

07 / 07

In short

  • xs[1:3] … from 1 up to just before 3
  • xs[:2] … from the front
  • xs[2:] … from there to the end
  • xs[:] … the whole thing (a copy)

That is the end of this group. In the next one you will see that exactly these numbers and slices work on text. name[0] is the first character, name[0:3] the first three. Look forward to how much less there is to learn.