What is the meaning of int(a[::-1]) in Python?

What is the meaning of int(a[::-1]) in Python?

Assuming a is a string. The Slice notation in python has the syntax –


So, when you do a[::-1], it starts from the end towards the first taking each element. So it reverses a. This is applicable for lists/tuples as well.

Example –

>>> a = 1234
>>> a[::-1]

Then you convert it to int and then back to string (Though not sure why you do that) , that just gives you back the string.

The notation that is used in


means that for a given string/list/tuple, you can slice the said object using the format

<object_name>[<start_index>, <stop_index>, <step>]

This means that the object is going to slice every step index from the given start index, till the stop index (excluding the stop index) and return it to you.

In case the start index or stop index is missing, it takes up the default value as the start index and stop index of the given string/list/tuple. If the step is left blank, then it takes the default value of 1 i.e it goes through each index.


a = 1234
print a[::2]

would print


Now the indexing here and also the step count, support negative numbers. So, if you give a -1 index, it translates to len(a)-1 index. And if you give -x as the step count, then it would step every xth value from the start index, till the stop index in the reverse direction. For example

a = 1234
print a[3:0:-1]

This would return


Note, that it doesnt return 4321 because, the stop index is not included.

Now in your case,


would just reverse a given integer, that is stored in a string, and then convert it back to a string

i.e 1234 -> 4321 -> 4321 -> 4321

If what you are trying to do is just reverse the given string, then simply a[::-1] would work .

What is the meaning of int(a[::-1]) in Python?

Leave a Reply

Your email address will not be published. Required fields are marked *