Reverse a Tuple in Python
Tuple in Python:
In Python, a tuple is an ordered, immutable, and heterogeneous collection of elements. Tuples often store related information, such as a person's name, age, date, and weather conditions. Objects are divided up into groups called Python Tuples by commas. In terms of repetition, nested objects, and indexing, a tuple and a list resemble each other in some ways, but just a tuple is immutable while a list is mutable. Multiple items can be stored in one variable by using tuples. One of the four built-in types of data in Python for storing data collections is the tuple; the other three are list, set, and dictionary, each with a unique set of features and applications. A tuple is an unchangeable, ordered collection. One of the primary container data structures offered by Python is the tuple. Typically, they are made using standard parentheses (). They are heterogeneous because they are container data types, which can hold various items and permit items of various data types.
What is Immutable mean?
If we want to append to a tuple using Python, this presents a problem. According to the Python documentation, immutable properties cannot be changed. In reality, changing (or mutating) an object is what we do when we wish to append a value to it. As a result, throughout this tutorial, whenever we talk about adding to a tuple in Python, we mean adding a value to an already-existing tuple by making a new object.
CODE:
#creating a tuple s
s= (4,5,6)
print(s)
print(type(s))
OUTPUT:
(4, 5, 6)
<class 'tuple'>
CODE EXPLANATION:
This code creates a tuple s with the elements 4, 5, and 6 and then prints the tuple and its type. The first line of the code s = (4, 5, 6) creates a tuple named s with the values 4, 5, 6. The second line print(s) displays the tuple s on the screen, which will output (4, 5, 6). The third line print(type(s)) displays the data type of the variable s, which will output <class 'tuple'>. This tells us that s is an object of the tuple class.
Accessing Values in Python Tuples:
Accessing tuple values using an index:
CODE:
tup = ("hey", "How", "are You!")
print("Value in tup[0] = ", tup[0])
print("Value in tup[1] = ", tup[1])
print("Value in tup[2] = ", tup[2])
OUTPUT:
Value in tup[0] = hey
Value in tup[1] = How
Value in tup[2] = are You!
We used the positive index in the methods above to access the needed value from a tuple in Python. Here, we will use the -ve index within Python.
CODE EXPLANATION:
This code creates a tuple tup with the elements "hey", "How", "are You!", and then accesses and prints the elements of the tuple using indexing. The first line tup = ("hey", "How", "are You!") creates a tuple named tup with the values "hey", "How", "are You!". The next three lines print("Value in tup[0] = ", tup[0]), print("Value in tup[1] = ", tup[1]), and print("Value in tup[2] = ", tup[2]) access the individual elements of the tuple using indexing and print the values of the elements. In Python, tuples are zero-indexed, which means that the first element has an index of 0, the second element has an index of 1, and so on. To access an element of a tuple, you use the index of that element inside square brackets []. So, tup[0] accesses the first element of the tuple tup, which is "hey". tup[1] accesses the second element, which is "How", and tup[2] accesses the third element, which is "are You!".
Reversing a tuple:
Reversing a tuple using a Built-in Function:
CODE:
def reverse_tuple(t):
return tuple(reversed(list(t)))
my_tuple = (5,4,3,2,1)
reversed_tuple = reverse_tuple(my_tuple)
print("Original Tuple:", my_tuple)
print("Tuple after Reversing:", reversed_tuple)
OUTPUT:
Original Tuple: (5, 4, 3, 2, 1)
Tuple after Reversing: (1, 2, 3, 4, 5)
CODE EXPLANATION:
This code defines a function reverse_tuple that takes a tuple as an argument and returns a reversed version of that tuple. The function reverse_tuple first converts the input tuple t to a list using the list() function. Then, it reverses the list using the reversed() function. Finally, it converts the reversed list back to a tuple using the tuple() function and returns the result. The code then creates a tuple my_tuple with the values 5, 4, 3, 2, and 1 and assigns it to the variable my_tuple. The line reversed_tuple = reverse_tuple(my_tuple) calls the reverse_tuple function with my_tuple as an argument and assigns the result to the variable reversed_tuple. Finally, the code prints the original and reversed tuple using the print() function.
To reverse a tuple in Python, we'll use the following techniques:
- Using Slicing
- Using reversed() method
- Using a Generator in Python
- Using the indexing technique
Slicing method for Reversing a tuple:
CODE:
def reverse_tuple(tup):
return tup[::-1]
tup = (1, 2, 3, 4, 5)
print("Original Tuple:")
print(tup)
print("Tuple after Reversing:")
print(reverse_tuple(tup))
OUTPUT:
Original Tuple:
(1, 2, 3, 4, 5)
Tuple after Reversing:
(5, 4, 3, 2, 1)
CODE EXPLANATION:
The slicing syntax used in the function is tup[::-1]. The colon: in slicing indicates that we're creating a slice, and the two dots .. after the colon indicate that we include all the elements in the slice. The -1 after the two dots is the step, and a step of -1 means that the slice will start from the end of the tuple and work backwards to the start of the tuple, effectively reversing the order of the elements.
After the function definition, the code creates a tuple tup = (1, 2, 3, 4, 5) and prints its original value using print("Original Tuple:") and print(tup). Finally, it calls the reverse_tuple function with tup as an argument and prints the result using print("Tuple after Reversing:") and print(reverse_tuple(tup)).
Reversed method for Reversing a tuple:
CODE:
tuple_values = (3,2,"rohith",12)
print("The original tuple: ", tuple_values)
tuple_values = tuple(reversed(tuple_values))
print("Tuple after reversing ", tuple_values)
OUTPUT:
The original tuple: (3, 2, 'rohith', 12)
Tuple after reversing (12, 'rohith', 2, 3)
CODE EXPLANATION:
This code creates a tuple called tuple_values with the elements (3,2, "rohith",12), then reverses the tuple’s elements using the reversed function. The first print statement outputs the original tuple using the string "The original tuple: " and the tuple_values variable. The second line of code uses the reversed function to reverse the elements of the tuple. The reversed function returns an object that can be iterated over to produce the input elements in reverse order, but it is not a tuple itself. To convert this object back into a tuple, the tuple function is used on the result of reversal. The reversed tuple is then assigned back to the tuple_values variable. The third print statement outputs the reversed tuple using the string "Tuple after reversing " and the tuple_values variable.
Using Generator in Python:
tuple = (3,2,"rohith",12)
print("The original tuple is: ", tuple)
def reverse_tup(tuple_values):
for i in reversed(range(len(tuple))):
yield tuple[i]
#Reversing the order of the items
for i in reverse_tup(tuple):
print("The element of a reversed tuple is: ", i)
OUTPUT:
The original tuple is: (3, 2, 'rohith', 12)
The element of a reversed tuple is: 12
The element of a reversed tuple is: rohith
The element of a reversed tuple is: 2
The element of a reversed tuple is: 3
CODE EXPLANATION:
The reversed function generates an iterable that produces the values of range(len(tuple)) in reverse order. The range function generates a sequence of integers from 0 to len(tuple) - 1, where len(tuple) is the number of elements in the tuple. The for loop in the generator function iterates over the elements of reversed(range(len(tuple))) and yields the corresponding elements of the tuple using the expression tuple[i].
After defining the generator function, the code uses another for loop to iterate over the values generated by reverse_tup(tuple). For each value, the code outputs the value using the print statement print("The element of a reversed tuple are: ", i).
Using the indexing technique:
tuple=(3,2,"rohith",12.3)
print("The original tuple is: ", tuple)
for i in range(len(tuple)):
print("The element of a reversed tuple is: ", tuple[-(i+1)])
OUTPUT:
The original tuple is: (3, 2, 'rohith', 12.3)
The element of a reversed tuple is: 12.3
The element of a reversed tuple is: rohith
The element of a reversed tuple is: 2
The element of a reversed tuple is: 3
CODE EXPLANATION:
The code then uses a for loop to iterate over the elements of the range(len(tuple)). For each iteration of the loop, the code prints the corresponding element of the reversed tuple using the print statement print("The element of a reversed tuple is: ", tuple[-(i+1)]). The expression tuple[-(i+1)] retrieves the i-th element from the end of the tuple. The variable i starts from 0 and increases by 1 for each loop iteration, so i+1 equals the element’s position from the end of the tuple.