Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this "[::-1]" return a reversed list in Python? [duplicate]

Possible Duplicate:
Good Primer for Python Slice Notation
reverse a string in Python

I've seen this syntax crop up in a few code snippets I've seen lately, and I'm curious as to what it does. If I have my_list = [1,2,3,4,5], and I execute my_list[::-1], I'm given a list with the elements reversed [5,4,3,2,1]. Could someone please explain to me what this actually does, and show the difference between [:] notation and [::]? Or at least refer me to a resource that does.

I'm sure if I had a good Python book it would be in there, but I don't. And it's impossible to search Google for something like this since the [::] gets ignored. Thanks!

like image 392
Nathan Jones Avatar asked Jun 22 '12 22:06

Nathan Jones


People also ask

What is __ reversed __ in Python?

Python reversed() method The reversed() method returns the reversed iterator of the given sequence. It is the same as the iter() method but in reverse order. Internally, it calls the __reversed__() method of the sequence class.

How is list Reverse different from list 1 in reference to Python list?

reverse reverses the list in-place, see the manual, while [::-1] gives a new list in reversed order.

What does reversed return in Python?

reversed in Python returns an iterator that accesses the given sequence in the reverse order.

Does list Reverse () method return a value?

Returns: The reverse() method does not return any value but reverses the given object from the list.


1 Answers

There is no difference between [:] and [::].

But [::-1] does something else: it has a negative step parameter. The absence of the start and stop parameters means the complete array. The negative step parameter means that data is taken in reverse order, from the end to the start.

like image 155
glglgl Avatar answered Sep 17 '22 01:09

glglgl