Python Python Sequences Sequence Operations Creating Slices

How do I know what elements I need?

I need to make a slice of the 3rd through 5th elements in the list. But does that mean 3rd starting at 1 like a human, or starting at 0 like Python? I tried slicing [3:6] and got an 'incorrect values' answer, so I tried [4:6] and [4:7] and got the same result.

slices.py
student_gpas = [4.0, 2.3, 3.5, 3.7, 3.9, 2.8, 1.5, 4.0]
sliced_gpas = student_gpas[4:6] 

1 Answer

Steven Parker
Steven Parker
207,981 Points

You're right about "starting at 0 like Python", so that means the third element would have an index of  2 . And since slices are exclusive of the stop value, and the final index should be 4, then the stop value is  5 .

sliced_gpas = student_gpas[2:5] 

I was adding 1 to the wrong number, oops. Thanks for breaking it down. Wish there was a better way to explain that we want the third item in the list according to humans, second according to Python.

Steven Parker
Steven Parker
207,981 Points

It's still the 3rd item to Python, it just starts counting with 0 for the first.