Reverse a tuple in PythonWe know that tuples are the data structures present in Python in which elements of different data types can be enclosed in parenthesis. In this tutorial, we will learn how we can reverse a tuple in Python. Consider the following examples to understand our objective- Explanation – We can observe here that since we have reversed the elements of the tuple, the float value present at the last comes in the first place. Let’s see one more example- Explanation – We can observe here that since we have reversed the elements of the tuple, the string value present at the last comes in the first place. We will use the following methods to reverse a tuple in Python,
So, let’s get started with the first one: Using SlicingThe slicing technique used in Python to slice the elements that lie in a specific range. The following program illustrates how they can be used. Output: The original tuple is: (1, 2, 'Python', 'Java', 23.4, 77, 10) The reversed tuple is: (10, 77, 23.4, 'Java', 'Python', 2, 1) Explanation- It’s time to have a look at the explanation of the above program-
In the second program, we will learn how method can be used. Using reversed() methodConsider the program given below, Output: The original tuple is: (1, 2, 'Python', 'Java', 23.4, 77, 10) The reversed tuple is: (10, 77, 23.4, 'Java', 'Python', 2, 1) Explanation- Let’s understand what happened in the above program,
In the third program, we will see how generators can be used for the same. Using Generator in PythonThe program given below demonstrates how generators can be used in our Python program. Output: The original tuple is: (1, 2, 'Python', 'Java', 23.4, 77, 10) The elements of a reversed tuple are: 10 The elements of a reversed tuple are: 77 The elements of a reversed tuple are: 23.4 The elements of a reversed tuple are: Java The elements of a reversed tuple are: Python The elements of a reversed tuple are: 2 The elements of a reversed tuple are: 1 Explanation- It’s time to have a glance at the explanation,
Finally, we will see how indexing can help us to meet our objective. Using the indexing techniqueThe following program illustrates how it can be done Output: The original tuple is: (1, 2, 'Python', 'Java', 23.4, 77, 10) The element of a reversed tuple is: 10 The element of a reversed tuple is: 77 The element of a reversed tuple is: 23.4 The element of a reversed tuple is: Java The element of a reversed tuple is: Python The element of a reversed tuple is: 2 The element of a reversed tuple is: 1 Explanation- It’s time to have a look at the explanation of the above program-
ConclusionIn this tutorial, we discussed the different approaches of reversing a tuple in Python. |
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/263361.html