# How to sort list by parameter in python? [closed]

I have a list of employee records. Each tuple of the list represent a person's record, which includes his name, ID, and age.

For example,

emp_records = [('Karim',100, 45), ('Rahim',10, 30),('Salim', 300,60),('Abu',50,35)]

Now, I want to sort emp_records based on ID.

You can use lambda function to pass argument by which you need to sort the records.

For example,

sorted_list=sorted(emp_records, key=lambda emp : emp[1])   //Here 1 means ID
print(sorted_list)


You can also use the operator module. The operator module has the itemgetter function, which takes item as argument and sort based on the argument

For example,

from operator import itemgetter
sorted_list=sorted(emp_records, key=itemgetter(1)) // Here 1 means ID
print(sorted_list)


Use the sorted function. It accepts key as argument.
You can then use a lambda to sort on the relevant index of your tuple.

sorted(emp_records, key=lambda x: x[1])