Open In App

Python | Ways to sort a zipped list by values

Last Updated : 20 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Zipped lists are those lists where several lists are mapped together to form one list which can be used as one entity altogether. In Python Zip() function is used to map different lists. Let’s discuss a few methods to demonstrate the problem. 
Method #1: Using lambda and sort 

Python3




# Python code to demonstrate
# sort zipped list by values
# using lambda and sorted
 
# Declaring initial lists
list1 = ['geeks', 'for', 'Geeks']
list2 = [3, 2, 1]
zipped = zip(list1, list2)
 
# Converting to list
zipped = list(zipped)
 
# Printing zipped list
print("Initial zipped list - ", str(zipped))
 
# Using sorted and lambda
res = sorted(zipped, key = lambda x: x[1])
     
# printing result
print("final list - ", str(res))


Output:

Initial zipped list -  [('geeks', 3), ('for', 2), ('Geeks', 1)]
final list -  [('Geeks', 1), ('for', 2), ('geeks', 3)]

Time Complexity: O(n*n), where n is the length of the list test_list 
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res list 

  Method #2: Using operator and sort 

Python3




# Python code to demonstrate
# sort zipped list by values
# using operator and sorted
 
import operator
# Declaring initial lists
list1 = ['akshat', 'Manjeet', 'nikhil']
list2 = [3, 2, 1]
zipped = zip(list1, list2)
 
# Converting to list
zipped = list(zipped)
 
# Printing zipped list
print("Initial zipped list - ", str(zipped))
 
# Using sorted and operator
res = sorted(zipped, key = operator.itemgetter(1))
     
# printing result
print("final list - ", str(res))


Output:

Initial zipped list -  [('akshat', 3), ('Manjeet', 2), ('nikhil', 1)]
final list -  [('nikhil', 1), ('Manjeet', 2), ('akshat', 3)]

Method #3: Using the zip and sorted functions with the key argument:

Approach:

  • Zip the two lists together using the zip function
  • Sort the zipped list using the sorted function with the key argument set to lambda x: x[1]
  • Unzip the sorted zipped list using the zip function with the * operator
  • Convert the unzipped result to a list

Python3




list1 = [1, 3, 5, 7]
list2 = [2, 4, 6, 8]
 
zipped = list(zip(list1, list2))
sorted_zipped = sorted(zipped, key=lambda x: x[1])
sorted_list1, sorted_list2 = zip(*sorted_zipped)
print(list(sorted_zipped))
print(list(sorted_list1))
print(list(sorted_list2))


Output

[(1, 2), (3, 4), (5, 6), (7, 8)]
[1, 3, 5, 7]
[2, 4, 6, 8]

Time complexity: O(n log n)
Space complexity: O(n)



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads