Open In App

Python | Integrity Sorting in two lists

Last Updated : 02 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Often during the problem solving we come across too many problems where we need to sort the list. But sometimes we would also want to sort the another list so that the elements of are automatically shifted and remain at same index as the first list even after first list get sorted. Let’s discuss certain ways in which this can be done. 
Method #1 : Using sorted() + zip() + itemgetter() Combining the three functions we can possibly achieve the task. The zip functions binds the two list together, sorted function sorts the list and itemgetter function is used to define the metrics against which we need second list to shift, in this case first list. 
 

Python3




# Python3 code to demonstrate
# integrity sorting in two list
# using sorted() + zip() + itemgetter()
from operator import itemgetter
 
# initializing lists
test_list1 = [3, 4, 9, 1, 6]
test_list2 = [1, 5, 3, 6, 7]
 
# printing original lists
print ("The original list 1 is : " + str(test_list1))
print ("The original list 2 is : " + str(test_list2))
 
# using sorted() + zip() + itemgetter()
# integrity sorting in two list
res = [list(x) for x in zip(*sorted(zip(test_list1, test_list2),
                                         key = itemgetter(0)))]
 
# printing result
print ("The lists after integrity sort : " +  str(res))


Output:

The original list 1 is : [3, 4, 9, 1, 6]
The original list 2 is : [1, 5, 3, 6, 7]
The lists after integrity sort : [[1, 3, 4, 6, 9], [6, 1, 5, 7, 3]]

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

  Method #2 : Using sorted() + zip() + lambda function This method performs the similar task, each function performing the similar function, the difference is just the instead of itemgetter function, lambda function performs the task of assigning a base to sort the list, i.e the first list in this case. 

Python3




# Python3 code to demonstrate
# integrity sorting in two list
# using sorted() + zip() + lambda function
from operator import itemgetter
 
# initializing lists
test_list1 = [3, 4, 9, 1, 6]
test_list2 = [1, 5, 3, 6, 7]
 
# printing original lists
print ("The original list 1 is : " + str(test_list1))
print ("The original list 2 is : " + str(test_list2))
 
# using sorted() + zip() + lambda function
# integrity sorting in two list
res = [list(i) for i in zip(*sorted(zip(test_list1, test_list2),
                                  key = lambda dual: dual[0]))]
 
# printing result
print ("The lists after integrity sort : " +  str(res))


Output:

The original list 1 is : [3, 4, 9, 1, 6]
The original list 2 is : [1, 5, 3, 6, 7]
The lists after integrity sort : [[1, 3, 4, 6, 9], [6, 1, 5, 7, 3]]

  Method #3 : Using numpy:

  1. Initialize two arrays, arr1 and arr2, with the values to be sorted.
  2. Use np.argsort() to obtain the sorted indices of the first array, arr1.
  3. Use the sorted indices to sort both arrays, arr1 and arr2, based on the values in arr1.
  4. Return the sorted arrays, arr1_sorted and arr2_sorted.
  5. And here is a brief description of what each line of code in the Python program is doing:
  6. Initialize the two arrays, arr1 and arr2.
  7. Use np.argsort() to obtain the sorted indices of the first array, arr1.
  8. Use the sorted indices to sort both arrays, arr1 and arr2, based on the values in arr1.
  9. Print the sorted arrays, arr1_sorted and arr2_sorted.

Python3




import numpy as np
 
# initializing arrays
arr1 = np.array([3, 4, 9, 1, 6])
arr2 = np.array([1, 5, 3, 6, 7])
  
# printing original lists
print ("The original list 1 is : " + str(arr1))
print ("The original list 2 is : " + str(arr2))
# sorting arrays based on first array
sorted_indices = np.argsort(arr1)
arr1_sorted = arr1[sorted_indices]
arr2_sorted = arr2[sorted_indices]
 
# printing result
print("The arrays after integrity sort:")
print(arr1_sorted)
print(arr2_sorted)
#This code is contributed by Jyothi pinjala


Output:
The original list 1 is : [3 4 9 1 6]
The original list 2 is : [1 5 3 6 7]
The arrays after integrity sort:
[1 3 4 6 9]
[6 1 5 7 3]

Time complexity:

The np.argsort() function has a time complexity of O(n log n) for an array of n elements.
The array indexing operation arr1[sorted_indices] has a time complexity of O(n).
The overall time complexity of the algorithm is O(n log n).
Auxiliary Space:

The algorithm uses extra memory for the sorted indices, sorted_indices, and the sorted arrays, arr1_sorted and arr2_sorted.
The space complexity is O(n) for these arrays.



Similar Reads

Verify Integrity of Files Using Digest in Python
Data integrity is a critical aspect of file management, ensuring that files remain unaltered during transmission or storage. In Python, one effective method to verify file integrity is by using cryptographic hash functions and their corresponding digests. A digest is a fixed-size string generated by a hash function, uniquely representing the conten
6 min read
How to Zip two lists of lists in Python?
The normal zip function allows us the functionality to aggregate the values in a container. But sometimes, we have a requirement in which we require to have multiple lists and containing lists as index elements and we need to merge/zip them together. This is quite uncommon problem, but solution to it can still be handy. Let's discuss certain ways i
7 min read
Different ways of sorting Dictionary by Keys and Reverse sorting by keys
Prerequisite: Dictionaries in Python A dictionary is a collection which is unordered, changeable and indexed. In Python, dictionaries are written with curly brackets, and they have keys and values. We can access the values of the dictionary using keys. In this article, we will discuss 10 different ways of sorting the Python dictionary by keys and a
8 min read
Different ways of sorting Dictionary by Values and Reverse sorting by values
Prerequisite: Dictionaries in Python A dictionary is a collection which is unordered, changeable, and indexed. In Python, dictionaries are written with curly brackets, and they have keys and values. We can access the values of the dictionary using keys. In this article, 10 different ways of sorting the Python dictionary by values and also reverse s
15+ min read
Python | Sorting list of lists with similar list elements
Sorting has always been a key operation that is performed for many applications and also as a subproblem to many problems. Many variations and techniques have been discussed and their knowledge can be useful to have while programming. This article discusses the sorting of lists containing a list. Let's discuss certain ways in which this can be perf
5 min read
Sorting List of Lists with First Element of Each Sub-List in Python
In Python, sorting a list of lists by the first element of each sub-list is a common task. Whether you're dealing with data points, coordinates, or any other structured information, arranging the lists based on the values of their first elements can be crucial. In this article, we will sort a list of lists by the first element of each sub-list. Thi
3 min read
Sorting Python Dictionary With Lists as Values
Python offers various methods to sort a dictionary with Lists as Values. This is a common task when dealing with data where you need to order elements based on different criteria. In this article, we will sort a dictionary with lists as values in Python. Sort a Dictionary with Lists as Values in PythonBelow, are the ways to Sort a Dictionary Python
3 min read
Python | Program to count number of lists in a list of lists
Given a list of lists, write a Python program to count the number of lists contained within the list of lists. Examples: Input : [[1, 2, 3], [4, 5], [6, 7, 8, 9]] Output : 3 Input : [[1], ['Bob'], ['Delhi'], ['x', 'y']] Output : 4 Method #1 : Using len() C/C++ Code # Python3 program to Count number # of lists in a list of lists def countList(lst):
5 min read
Python - Convert Lists into Similar key value lists
Given two lists, one of key and other values, convert it to dictionary with list values, if keys map to different values on basis of index, add in its value list. Input : test_list1 = [5, 6, 6, 6], test_list2 = [8, 3, 2, 9] Output : {5: [8], 6: [3, 2, 9]} Explanation : Elements with index 6 in corresponding list, are mapped to 6. Input : test_list1
12 min read
Indexing Lists Of Lists In Python
Lists of lists are a common data structure in Python, providing a versatile way to organize and manipulate data. When working with nested lists, it's crucial to understand how to index and access elements efficiently. In this article, we will explore three methods to index lists of lists in Python using the creation of a sample list, followed by ex
3 min read