Facebook Twitter Instagram
    Facebook Twitter Instagram Pinterest Vimeo
    Hand On CodeHand On Code
    Hand On CodeHand On Code
    Home»python»How to Sort Tuple in Python
    python

    How to Sort Tuple in Python

    April 7, 2023No Comments4 Mins Read
    Share
    Facebook Twitter LinkedIn Pinterest Email

    Python Tuple Sorting Guide

    Tuples are a special kind of data type for variables that allow us to store an array of objects. A tuple is a sequence of objects that is both ordered and immutable (whose components cannot be changed). One of Python’s built-in data structures for storing items is a tuple, while the other three are List, Dictionary, and Set. The text is spherical because

    brackets.

    Sorting a Tuple in Python

    Using sort()

    By default, the sort() function will sort a list’s components in ascending order, starting with the first entry. With this method, we may sort a tuple by first converting it to a list. This method returns None after sorting the list in place. Input

    Resulting



    1. tuple_ = (


      ‘Itika’


      ,


      ‘Arshia’


      ,


      ‘Peter’


      ,


      ‘Parker’


      )


    2. list(tuple_).sort()

    3. print(tuple_)

    4. print(type(tuple_))

    :

    ('Itika', 'Arshia', 'Peter', 'Parker')
    <class 'tuple'>
    

    Using sorted()

    To sort a Tuple in Python, you may use the sorted() built-in method. The tuple is an argument that must be given to the sorted() method. By default, the method returns a list where the tuple elements are arranged in ascending order. A tuple may be used to transform a list into a tuple ().

    The sorted() function allows an additional sorting order specification through the function’s reverse argument. By default, lists are sorted upwards. When reverse=True is used, the items are sorted into a descending order. The returned values from a key function that we designate may also be utilized to sort the data. In the following code, we take a tuple, tuple_, with integer values and sort it in ascending order. Input

    Resulting



    1. tuple_ = (


      5


      ,


      2


      ,


      24


      ,


      3


      ,


      1


      ,


      6


      ,


      7


      )


    2. sorted_ = tuple(sorted(tuple_))

    3. print(

      ‘Sorted Tuple :’


      , sorted_)


    4. print(type(sorted_))

    :

    Sorted Tuple : (1, 2, 3, 5, 6, 7, 24)
    <class 'tuple'>
    

    The tuple is now being sorted by the same function, but in descending order. To sort the tuple in descending order, you may use the reverse=True parameter with the sorted() method. Input

    Results from a



    1. tuple_ = (


      5


      ,


      2


      ,


      24


      ,


      3


      ,


      1


      ,


      6


      ,


      7


      )


    2. sorted_ = tuple(sorted(tuple_, reverse=True))

    3. print(

      ‘Sorted Tuple :’


      , sorted_)


    4. print(type(sorted_))

    Processor:

    Sorted Tuple : (24, 7, 6, 5, 3, 2, 1)
    <class 'tuple'>
    

    Sorting a Tuple Based on a Key Function

    A key is a function that accepts one value as input and returns another as output. This key function is applied to each element in the tuple, and the resulting value is then utilized as a comparison for sorting. In the following code, we use the strings’ lengths to sort a tuple of strings. One such solution is to utilize the len() built-in function. Input

    Resulting



    1. tuple_ = (


      ‘abhd’


      ,


      ‘sbchcwsc’


      ,


      ‘sjs’


      ,


      ‘sxshs’


      )


    2. sorted_ = tuple(sorted(tuple_, key=len))

    3. print(

      ‘Sorted Tuple :’


      , sorted_)


    4. print(type(sorted_))
    Sorted Tuple : ('sjs', 'abhd', 'sxshs', 'sbchcwsc')
    <class 'tuple'>
    

    Sorting List of Tuples

    Using sorted()

    Let’s have a look at how to use a tuple to sort a list in Python. Let’s pretend we’re in this situation: we need to sort the list of tuples. Any provided key must be used to sort tuples. To do this, you may use the sorted() method, which sorts objects according to a key and saves the index of the key used to sort the supplied tuples. Python code for this method looks like this: Input

    Resulting



    1. # Sorting list of tuples according to a key


    2. def middle(n):


    3. return


      n[


      1


      ]



    4. # function to sort the tuple

    5. def sort(list_of_tuples):


    6. return


      sorted(list_of_tuples, key = middle)



    7. # driver code

    8. list_ = [(

      34


      ,


      21


      ,


      56


      ), (


      24


      ,


      12


      ,


      32


      ), (


      42


      ,


      34


      ,


      42


      ), (


      27


      ,


      11


      ,


      32


      )]



    9. print(

      “Sorted list of Tuples:”


      ),


    10. print(sort(list_))

    :

    Sorted list of Tuples:
    [(27, 11, 32), (24, 12, 32), (34, 21, 56), (42, 34, 42)]
    

    Using Bubble Sort

    Bubble sort is just a sorting technique that may be applied to a list of any size. If two items next to each other in a list are in the wrong order, it will switch them. The procedure is then repeated until all of the components have been categorized.

    Here, we’ll demonstrate how to sort a collection of tuples using the bubble sort method. Input

    Resulting



    1. roll = [(


      ‘Arshia’


      ,


      26


      ), (


      ‘Itika’


      ,


      53


      ), (


      ‘Peter’


      ,


      82


      ), (


      ‘Parker’


      ,


      74


      ), (


      ‘MJ’


      ,


      45


      )]


    2. first =

      0




    3. last = len(roll)


    4. for


      k in range(


      0


      , last):



    5. for


      l in range(


      0


      , last-k-


      1


      ):



    6. if


      (roll[l][first] > roll[l +


      1


      ][first]):


    7. new_item = roll[l]

    8. roll[l]= roll[l +

      1


      ]


    9. roll[l +

      1


      ]= new_item


    10. print(roll)
    [('Arshia', 26), ('Itika', 53), ('MJ', 45), ('Parker', 74), ('Peter', 82)]
    
    How to Sort Tuple in Python Learn Python free Python Code Python Course Free download python coursefree Courses Download Python Language
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Previous ArticlePython Update MySQL Table
    Next Article Python GUI Programming With Tkinter Quiz

    Related Posts

    python

    Class method vs Static method in Python

    April 7, 2023
    python

    Python Program to Count the Number of Matching Characters in a Pair of String

    April 7, 2023
    python

    Coroutine in Python

    April 7, 2023
    Add A Comment

    Leave A Reply Cancel Reply

    Facebook Twitter Instagram Pinterest
    © 2023 ThemeSphere. Designed by ThemeSphere.

    Type above and press Enter to search. Press Esc to cancel.