Hackforge Academy

Category: python

The key Parameter

Published on 27 Oct 2026

Explanation

sorted() returns a new list and uses key to calculate a sorting value for each item.

Code:

names = ['Kumar', 'Arun', 'Priya', 'Raj']
print(sorted(names, key=len))

Explanation

reverse=True sorts in descending order; default sorting is ascending.

Code:

numbers = [40, 10, 30, 20]
print(sorted(numbers))
print(sorted(numbers, reverse=True))

Explanation

A key function can extract a field from each dictionary or object.

Code:

students = [{'name': 'Arun', 'marks': 85}, {'name': 'Priya', 'marks': 95}]
print(sorted(students, key=lambda s: s['marks']))

Explanation

Return a tuple from key to sort by multiple criteria; fields are compared from left to right.

Code:

students = [{'name': 'Arun', 'marks': 90}, {'name': 'Priya', 'marks': 90}, {'name': 'Kumar', 'marks': 80}]
print(sorted(students, key=lambda s: (-s['marks'], s['name'])))

Explanation

sorted() creates a new list from an iterable; list.sort() modifies the existing list in place and returns None.

Code:

numbers = [5, 2, 8, 1]
new_list = sorted(numbers)
numbers.sort(reverse=True)
print(new_list, numbers)

πŸš€ Learn Spring Boot with real-world projects

πŸ’‘ Build REST APIs step by step

🧠 Improve backend development skills

🎯 Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

🐍

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
βš›οΈ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
β˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community