What does [::-1} do?
1 min readMay 9, 2023
The syntax [::-1]
is used in Python to create a reversed copy of a sequence, such as a string, list, or tuple. It is called extended slicing and is a concise way to reverse the order of elements in the sequence.
Here’s how it works:
- When used with a positive step value (1), like
[::-1]
, it returns a new sequence with elements in reverse order.
For example, consider a string hello = "Hello, World!"
. Using hello[::-1]
will give you a new string '!dlroW ,olleH'
, which is the reversed version of the original string.
- If you have a list or tuple, the behavior is the same. For instance, given a list
numbers = [1, 2, 3, 4, 5]
,numbers[::-1]
will produce[5, 4, 3, 2, 1]
, which is a reversed copy of the original list. - You can also use
[start:end:step]
to extract a subsequence with a reversed order. For instance,hello[7:12:-1]
will return'W ,ol'
, which is a subsequence consisting of characters from index 7 to 12 (exclusive) in reverse order.
Overall, [::-1]
is a useful syntax in Python for quickly reversing a sequence without modifying the original object.