Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Python Sequences Sequence Operations Slices

I don't get why [::-1] reversed the list

I am aware of other statements and functions that can easily reverse lists permanently or temporarily, why do it this way?

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 67,736 Points

Hey nicolaspeterson, good question!

A slice is one of the common sequence operations that may be applied to a list. The step size of a slice gives it power to skip some values. And the negative step means simply to count relative to the end instead of the list beginning. Being able get every other item from the end of a list might be useful.

The fact that a step of -1 with default start and step values functions equivalently as a reversal is merely convenient syntax sugar. This alternative reversal is well recognized Python idiom.

The slice trick has the advantage of returning a new list and leaving the original list unaltered. The list .reverse() method changes the original list in-place.

Post back if you need more help. Good luck!!!