w3resource

Python: Get a list, sorted in increasing order by the last element in each tuple from a given list of non-empty tuples

Python List: Exercise-6 with Solution

Write a Python program to get a list, sorted in increasing order by the last element in each tuple from a given list of non-empty tuples.

Visual Presentation:

Python List: Get a list, sorted in increasing order by the last element in each tuple from a given list of non-empty tuples

Sample Solution:

Python Code:

# Define a function called 'last' that takes a single argument 'n' and returns the last element of 'n'
def last(n):
    return n[-1]

# Define a function called 'sort_list_last' that takes a list of tuples 'tuples' as input
def sort_list_last(tuples):
    # Sort the list of tuples 'tuples' using the 'last' function as the key for sorting
    return sorted(tuples, key=last)

# Call the 'sort_list_last' function with a list of tuples as input and print the sorted result
print(sort_list_last([(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)]))

Sample Output:

[(2, 1), (1, 2), (2, 3), (4, 4), (2, 5)] 

Explanation:

In the above exercise -

def last(n): 
    return n[-1]

In the above code we define a function called 'last' that takes a single argument n. This function returns the last element of 'n'.

def sort_list_last(tuples):
  return sorted(tuples, key=last)

In the above code we define a function called 'sort_list_last' that takes a single argument tuples. This function sorts the input list of tuples based on the last element of each tuple, using the sorted function and the key parameter. The key parameter specifies a function to be called on each element of the list to determine the sort order. In this case, the 'last' function is used as the key function, so the sorting is based on the last element of each tuple.

print(sort_list_last([(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)]))  -> This line calls the sort_list_last function and passes in a list of tuples [(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)]. The resulting sorted list of tuples is then printed to the console using the print function. In this case, the expected output would be [(2, 1), (1, 2), (2, 3), (4, 4), (2, 5)].

Flowchart:

Flowchart: Get a list, sorted in increasing order by the last element in each tuple from a given list of non-empty tuples

Python Code Editor:

Previous: Write a Python program to count the number of strings where the string length is 2 or more and the first and last character are same from a given list of strings.
Next: Write a Python program to remove duplicates from a list.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/list/python-data-type-list-exercise-6.php