

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to sort the objects in a list in Python?
To sort a list of ints, floats, strings, chars or any other class that has implemented the __cmp__ method can be sorted just by calling sort on the list. If you want to sort the list in reverse order(descending), just pass in the reverse parameter as well.
example
my_list = [1, 5, 2, 6, 0] my_list.sort() print(my_list) my_list.sort(reverse=True) print(my_list)
Output
This will give the output −
[0, 1, 2, 5, 6] [6, 5, 2, 1, 0]
Since tuples are immutable, they don't have an in-place sort function that can be called directly on them. You have to use the sorted function, which returns a sorted list. If you dont want to sort the list in place, use sorted in place of the list class method sort.
example
my_list = [1, 5, 2, 6, 0] print(sorted(my_list)) print(sorted(my_list, reverse=True))
Output
This will give the output −
[0, 1, 2, 5, 6] [6, 5, 2, 1, 0]
If you have a list of objects without __cmp__ method implemented in the class, you can use the key argument to specify how to compare 2 elements. For example, if you have dictionaries in a list and want to sort them based on a key size, you could do the following:
Example
def get_my_key(obj): return obj['size'] my_list = [{'name': "foo", 'size': 5}, {'name': "bar", 'size': 3}, {'name': "baz", 'size': 7}] my_list.sort(key=get_my_key) print(my_list)
Output
This will give the output −
[{'name': 'bar', 'size': 3}, {'name': 'foo', 'size': 5}, {'name': 'baz', 'size': 7}]
It would call the function specified for each entry and sort based on this value for each entry. You could also specify the same function for an object as well, by returning an attribute of the object.
- Related Questions & Answers
- How to reverse the objects in a list in Python?
- How to append objects in a list in Python?
- How to shuffle a list of objects in Python?
- How to sort a list of strings in Python?
- How to sort a Python date string list?
- Python How to sort a list of strings
- How to sort a list in C#?
- Sort a list according to the Length of the Elements in Python program
- Python program to sort a list according to the second element in the sublist.
- How to access Python objects within objects in Python?
- Python program to sort a list according to the second element in sublist
- Python program to sort a List according to the Length of the Elements?
- Python – Sort by Units Digit in a List
- How to use LINQ to sort a list in C#?
- Python program to sort a list of tuples alphabetically