Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Python | Reversing a Tuple

  • Last Updated : 27 Dec, 2017

As we know that in Python, tuples are immutable, thus it cannot be changed or altered. This provides us with limited ways of reversing a tuple, unlike a list. We will go through few techniques on how a tuple in python can be reversed.

Input : tuples = ('z','a','d','f','g','e','e','k')
Output : ('k', 'e', 'e', 'g', 'f', 'd', 'a', 'z')

Input : tuples = (10, 11, 12, 13, 14, 15)
Output : (15, 14, 13, 12, 11, 10)

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course

Method 1: Using the slicing technique.
In this technique, a copy of the tuple is made and the tuple is not sorted in-place. Since tuples are immutable, there is no way to reverse a tuple in-place. Creating a copy requires more space to hold all of the existing elements. Therefore, this exhausts memory.

# Reversing a tuple using slicing technique
# New tuple is created
def Reverse(tuples):
    new_tup = tuples[::-1]
    return new_tup
# Driver Code
tuples = ('z','a','d','f','g','e','e','k')


('k', 'e', 'e', 'g', 'f', 'd', 'a', 'z')

Method 2: Using the reversed() built-in function.
In this method, we do not make any copy of the tuple. Instead, we get a reverse iterator which we use to cycle through the tuple, similar to the list.

# Reversing a list using reversed()
def Reverse(tuples):
    new_tup = ()
    for k in reversed(tuples):
        new_tup = new_tup + (k,)
    print new_tup
# Driver Code
tuples = (10, 11, 12, 13, 14, 15)


(15, 14, 13, 12, 11, 10)

My Personal Notes arrow_drop_up
Recommended Articles
Page :