Meaning of [::-1] in Python Slicing


The [::-1] can be used in Python as a concept of slicing with strings, lists or tuples, before you know what it is let's take a look at the slicing syntax.


Syntax
sequence[start:stop:step]
ParameterDescriptionDefault Value
startStarting index of the slice (inclusive)0
endEnding index of the slice (exclusive)Length of sequence
stepStep size between elements in the slice1

Now let's take an example of [::-1] with string

name="John"

print(name[::-1])

Result ==> nhoJ


string[::-1]

SliceResultDescription
sequence[::-1]Reversed sequenceReturns a new sequence with items in reverse order.

Now let's see an example with a list

numbers = [1, 2, 3, 4, 5]

reversed_numbers = numbers[::-1]

print(reversed_numbers)

Result:
[5,4,3,2,1]

Conclusion: tl;dr

[::-1] reverses the sliced string, list or tuple!

Example of colon colon -1 slicing in Python
-

Facing issues? Have Questions? Post them here! I am happy to answer!


Author Info:

Rakesh is a seasoned developer with over 10 years of experience in web and app development, and a deep knowledge of operating systems. Author of insightful How-To articles for Code2care.

Follow him on: X

Copyright © Code2care 2023 | Privacy Policy | About Us | Contact Us | Sitemap