← Back to Python Course | Chapter 14: Advanced Python & Tools | Lesson 9 of 15

Python sorted() और key Functions

sorted() चीज़ों को क्रम में लगाता है, और एक key function उसे बताता है कि order करते समय किस चीज़ को देखना है, बिल्कुल किसी class को नाम की बजाय ऊँचाई से sort करने जैसा। नियम आप चुनते हैं।
Syntax
python
sorted(iterable, key=function, reverse=False)
list_name.sort(key=function)

sorted() से Standard Sorting

sorted(iterable) एक बिल्कुल नई sorted list return करता है, original iterable को बिना छुए -- यह list के अपने .sort() method से अलग है, जो in place sort करता है और None return करता है।

गलत वाला चुनना उन confusing bugs का एक आम कारण है जहाँ कोई variable अचानक None बन जाता है।

उदाहरण: Standard Sorting with sorted()

python
numbers = [3, 1, 2]
result = sorted(numbers)  # returns a new sorted list
print(result, numbers)  # original list is untouched

Reverse Order में Sorting

sorted(), default रूप से elements को ascending order में रखता है; reverse=True पास करने से यह ascending sort करके फिर अलग से result को reverse करने की ज़रूरत के बिना, सीधे descending order में बदल जाता है।

उदाहरण: Sorting in Reverse Order

python
numbers = [3, 1, 2]
print(sorted(numbers, reverse=True))

Custom Key Functions से Sorting

key parameter एक ऐसा function accept करता है जो हर element पर लागू होकर comparison के लिए असल में इस्तेमाल होने वाली value compute करता है, जिससे आप elements के natural ordering की बजाय किसी derived property (जैसे किसी string की length) से sort कर सकते हैं।

उदाहरण: Sorting with Custom Key Functions

python
words = ["banana", "kiwi", "apple"]
print(sorted(words, key=len))

Lambda Keys से Sorting

key function inline देने का typical तरीका एक lambda है, खासकर tuples को उनके दूसरे element से sort करने जैसी सरल derivations के लिए, जैसे key=lambda x: x[1], बिना कहीं और अलग named function define करने के overhead के।

उदाहरण: Sorting with Lambda Keys

python
pairs = [(1, "b"), (2, "a")]
print(sorted(pairs, key=lambda x: x[1]))

Complex Lists को Sort करना

key का सबसे आम real-world इस्तेमाल dictionaries या custom objects की एक list को किसी specific field से sort करना है -- उदाहरण के लिए, sorted(people, key=lambda p: p[age]), person-records की एक list को उम्र से sort कर देता है, बिना यह बताने के अलावा कि कौन सा field मायने रखता है, किसी custom comparison logic की ज़रूरत के।

उदाहरण: Sorting Complex Lists

python
people = [{"name": "Alex", "age": 30}, {"name": "Sam", "age": 25}]
print(sorted(people, key=lambda p: p["age"]))
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.