itemgetter
like a magical hand 🖐️ that quickly grabs specific items (elements, fields, or values) from a list, tuple, or dictionary — without writing loops.It lives in the operator
module.
from operator import itemgetter
from operator import itemgetter
fruits = ["🍎 Apple", "🍌 Banana", "🍇 Grapes"]
get_first = itemgetter(0) # Grab item at index 0
get_two = itemgetter(0, 2) # Grab multiple indices
print(get_first(fruits)) # 🍎 Apple
print(get_two(fruits)) # ('🍎 Apple', '🍇 Grapes')
📌 Colorful Analogy:
Imagine you’re at a fruit basket 🧺, and you tell the vendor:
👉 "Give me the 1st and 3rd fruit only."
That’s exactly what itemgetter
does!
itemgetter
really shines when sorting lists of tuples or dictionaries.
from operator import itemgetter
students = [
("Abhi", 85),
("Neha", 92),
("Ravi", 78)
]
# Sort by marks (index 1)
sorted_students = sorted(students, key=itemgetter(1))
print(sorted_students)
# [('Ravi', 78), ('Abhi', 85), ('Neha', 92)]
📌 Colorful Analogy:
Think of students standing in line 🧑🤝🧑.
You say: "Arrange them based on marks only 🎯, not names."
That’s itemgetter(1)
in action!
from operator import itemgetter
person = {"name": "Abhi", "age": 32, "city": "Delhi"}
get_name_city = itemgetter("name", "city")
print(get_name_city(person)) # ('Abhi', 'Delhi')
📌 Colorful Analogy:
Like picking fields from a form 📋 –
👉 "I only need name and city, skip the rest."
itemgetter
?✅ Cleaner & faster than writing custom lambdas
✅ Works great for sorting & filtering
✅ Makes code readable & Pythonic ✨
lambda
vs itemgetter
Approach | Code | Output |
---|---|---|
Lambda ✍️ | sorted(students, key=lambda x: x[1]) |
✅ Works |
Itemgetter ⚡ | sorted(students, key=itemgetter(1)) |
✅ Shorter, Faster |
💡 In short:
👉 itemgetter
= a smart shortcut to grab or sort items without messy code. 🚀