This article will explain 2 different methods of reversing a tuple in python.

Method 1: Using slicing
Slicing in python is used to extract elements from a collection such as a list, string or tuple. Slicing is performed using element indexes enclosed between square brackets.
Syntax of slicing a tuple is

tuple[start_index: stop_index: step_size]

where elements are extracted from start_index till stop_index at an interval of step_size.

If start_index is omitted, then it defaults to 0, end_index is omitted, it is considered as end of tuple and step_size is taken as 0, if omitted.

Python also supports negative slicing which means that elements can be extracted from right to left.
If we omit start_index and end_index while set the step_size as -1, then it extracts the elements from right to left and hence reverses the tuple. Example,

# define a tuple
t = (1, 2, 3, 4, 5)
# slice tuple
r = t[::-1]
print('Original tuple:', t)
print('Reversed tuple:', r)

which prints

Original tuple: (1, 2, 3, 4, 5)
Reversed tuple: (5, 4, 3, 2, 1)

To know more about slicing, refer this article.

Method 2: Using reversed() function
Python’s inbuilt reversed() function accepts a tuple and returns a reverse iterator. This reverse iterator can be used to create a new tuple with elements in reverse direction as shown below.

#define a tuple
t = (1, 2, 3, 4, 5)
# create reverse iterator
reverse_iterator = reversed(t)
# create a new reversed tuple
r = tuple(reverse_iterator)
print('Original tuple:', t)
print('Reversed tuple:', r)

If you print the type of value returned by reversed() using type() function, then it will be

<class ‘reversed’>

which is an object of reversed class.

Hope the article was useful.

1
Close Menu

Never Miss an article !

Get the new post delivered straight into your inbox, enter your email and hit the button

You have successfully subscribed to the newsletter

There was an error while trying to send your request. Please try again.

codippa will use the information you provide on this form to be in touch with you and to provide updates and marketing.