DEV Community

Lalit Kumar
Lalit Kumar

Posted on

Python sort list of tuples by first element

In this post i will tell you about “python sort list of tuples by first element” which is easy and need just basic knowledge. A tuple is defined as a collection that is ordered and unchangeable.

DEFINITION ABOUT TUPLE

In Python programming language, tuples are written within round brackets.

  • Tuple is defined as a collection that is ordered nd’ unchangeable. It allows doing duplicate members.
  • Example TUPLE.
  • thistuple = ("sun", "moon", "stars") print(thistuple)

title: "originally posted here 👇"

canonical_url: https://kodlogs.com/blog/2600/python-sort-list-of-tuples-by-first-element

Python sort lists of tuples by first element...

If a list of tuples are given, write a Python program to sort the tuples by first element of every tuple.

Access

first element of each tuple using the nested loops.

Reverse : To sort these in ascending order we could have just Python.

Remove tuple having duplicate first value from given list of Sorting that list of numbers / characters is easy.

We can use sort() method / sorted() built-in function. In this , we want to sort a list of tuples by first value in the tuple.

Example- Let’s consider a tuple list having actor’s charater in a movie and his real name. [(Robert Downey Jr, "Ironman"), (Chris Evans, "Captain America")]

Method of Executing

Method: Using sort() method

When we sort via this method the actual content of the tuple is changed, just like the previous method, the in-place method of sort is executed.

Example:

# Python programming code to sort a list of tuple by the first element using sort()  

# Functions to sort the list by first element of tuple 

def Sort_Tuple(tup):  

    # reverse = None (get sorted in Ascending order)  
    # key is a set to sort using second element of  
    # sublist lambda is used  
    tup.sort(key = lambda x: x[1])  
    return tup  

# Driver Code  
tup = [('saket', 10), ('tony', 5), ('steve', 20), ('bahubali', 15)]  

# print the sorted list of tuples 
print(Sort_Tuple(tup))  
Enter fullscreen mode Exit fullscreen mode

Output:

[('tony', 5), ('saket', 10), ('bahubali', 15), ('steve', 20)]

Top comments (0)