How to print reverse tuple in Python

Hello readers, today we are going to discuss how to print reverse tuple in Python.

Printing reverse tuple in Python

Let’s consider a tuple tup.

tup = (1,2,3,4,5,6)

Our goal is to print the tuple in reverse order, that is (6,5,4,3,2,1)

Method1:

Using slicing method –[::-1]

Code:

def reverse_tuple(tup):
  tup = tup[::-1] #Using slicing method to reverse the tuple
  print(tup)
tup = (1,2,3,4,5,6)

reverse_tuple(tup)#Calling the function

Output:

(6, 5, 4, 3, 2, 1)

Method2:

Using extra space

Steps:

  • Declare a new tuple
  • Iterate the original tuple from last
  • Append each element in new tuple

Code:

def reverse_tuple(tup):
  k=()#New tuple
  for i in range(len(p)-1,-1,-1):

    k = k+ (p[i],) #Appending each element to new tuple
  print(k)
p = (1,2,3,4,5,6)
reverse_tuple(p)  #Calling the function

Output:

(6, 5, 4, 3, 2, 1)

Also read:

Thanks for reading!!!

Leave a Reply

Your email address will not be published.