Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Python Collections (2016, retired 2019) Slices Slicing With A Step

Bennett Lappen
Bennett Lappen
12,035 Points

Moving Backward Through List (slicing)

I'm confused at 2:51

The video states that we can't enter [-2:-5] when moving through the list because the list goes from left to right. However, we can enter [-2: -5: -1]. I don't understand .

Example: list1 = list(range(21)) list1 RETURNS [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]

list1 [-2 : -5] RETURNS nothing list1[-2 : -5 : -1] RETURNS [19, 18, 17]

I don't understand why [-2 : -5] does not work, while [-2 : -5: -1] does work. What's going on? The video explanation doesn't quite fill in the details for me.

Many thanks

1 Answer

Steven Parker
Steven Parker
231,236 Points

A negative value in a slice start or end argument means "from the end". So if you try to slice with [-2:-5], you are asking for everything starting 2 from the end, and going forwards to 5 from the end. Since the specified start position is already past the endl position, the result is empty.

On the other hand, if you specify [-2:-5:-1], you are asking for everything starting 2 from the end, and going backwards to 5 from the end. In that direction the start and end identify three values. If you wanted those same values in normal order you could ask for [-4:-1].

Does it make sense now?