Python sorted() और key Functions
In this page:
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()
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
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
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
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
people = [{"name": "Alex", "age": 30}, {"name": "Sam", "age": 25}]
print(sorted(people, key=lambda p: p["age"]))
Chapter Quiz — Complete all 15 topics to unlock
0/15 topics done
Complete these topics first:
- Python PEP 8 Style Guide
- Python Debugging Techniques
- Python Testing with unittest
- Python Common Mistakes
- Python Interview Questions
- Python map() & filter()
- Python reduce()
- Python zip() & enumerate()
- Python sorted() & key Functions
- Python Comprehensions Advanced
- Python Turtle Graphics
- Python tkinter Introduction
- Python tkinter Widgets
- Python pygame Introduction
- Python Mini Projects