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

Why use [:: -1] instead of reversed function?

In the video 'Slicing With A Step' Kenneth ends by showing how you can reverse a list with the command [: : -1], which slices an entire list and runs through it from end to beginning at a step of -1. However, this can also be done using the keyword "reversed". So,

new_thing = arg [::-1]

becomes

new_thing = list(reversed(arg))

The latter can only be used if you're slicing the entire list, with no steps involved, as it simply takes the whole list and reverses it. Other than that, however, what are the advantages to the reversed keyword as opposed to a full negative slice of the list?

There is no particular note-worthy benefit of using one or the other. Of course slicing gives you a little more flexibility, but for this exact exercise it is just a matter or taste. Perhaps the .reversed-method is a little more explanatory in terms of readable code.

1 Answer

Steven Parker
Steven Parker
243,656 Points

The slice method is more compact.

Plus it saves a step since it returns a list, but the reversed function output must be converted into a list.