Program to sort the first list using the second list using Python

by | Apr 15, 2021 | Python Programs

Home » Python » Python Programs » Program to sort the first list using the second list using Python

Introduction

In this section of python programming, we will understand the concept to sort the list based on the elements of the second list.

Program to sort the first list using the second list

Program

  1. Using zip()

def sort_list(list1, list2):

    zip_list = zip(list2, list1)

    x = [i for _, i in sorted(zip_list)]

    return x

   

list1 = ['v', 'i', 'b', 'g', 'y', 'o', 'r']

list2 = [0, 2, 1, 1, 2, 0, 1]

print("Sorted list", sort_list(list1, list2))

Output

Program to sort the first list using the second list Output 1

  1. Using Dictionary, list comprehension and lambda function

def sort_list(list1, list2):

# Blank dictionary and list

    new_dict = {}

    new_list = []

# Adding list1 and list2   

    new_dict = {list1[i]: list2[i] for i in range(len(list2))}

# Sorting   

    new_dict = {j : k for j, k in sorted(new_dict.items(), key = lambda item: item[1])}

# Append element in the list   

    for i in new_dict.keys():

        new_list.append(i)

    return new_list

   

list1 = ['red', 'yellow', 'black', 'blue', 'green', 'orange' ]

list2 = [00, 2, 1, 1, 2, 0]

print("Sorted list", sort_list(list1, list2))

Output

Program to sort the first list using the second list Output 2

Explanation

In the above python codes, we have used two approaches: 1. Using zip() function and 2. Using Python Dictionary, list comprehension and lambda function.

In approach 1, we zipped two lists (list1 and list2) using zip(). The zip() function maps the elements of similar index. The new sorted list is obtained using sorted() function on zipped list. The next step is to obtain the first lowest element of each pair, this is done by using list comprehension. And the sorted list is displayed on the screen.

From output, we can see that values are printed in ascending order of index values and alphabetical ordering. The first element is ‘v’ having the lowest index 0 and also ‘o’ has index value 0, but still ‘o’ is printed before ‘v’ because of the alphabetical ordering.

In approach 2, we have initialized dictionary new_dict and list new_list with empty values and added the elements of both the lists in the dictionary.  By using list comprehension and lambda function we sorted the elements based on key-value and append the elements in the list. The list is printed with the help of print() function.

We can see that the output of the second approach is something different. The difference is sorted list is only based on the index and follows left to right sorting of elements. The alphabetical ordering is not considered in this.

Author

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Author