LearningPython TutorialComprehensions, Lambda & Built-ins
CHAPTER 19 · CONCISE DATA TRANSFORMATIONS

Python Comprehensions, Lambda & Built-ins

Python readable shortcuts provide karta hai jo common loops, filtering, transformations aur sorting ko concise bana sakte hain. Is chapter me list/set/dict comprehensions, lambda functions, sorting keys aur practical built-ins ko readable code ke perspective se samjhenge.

English + Hinglish76 min readOnline practice included

Why these tools matter

Normal loops always valid hain. Comprehensions and built-ins un common patterns ko shorter form me express karte hain jahan intent clear rehta hai. Goal shortest code likhna nahi; goal readable aur predictable code likhna hai.

Hinglish Explanation

Agar 5-line loop ko 1-line comprehension me convert karne se code samajhna easy hota hai, use karo. Agar one-liner cryptic ho jaye, normal loop better hai.

List comprehensions

List comprehension existing iterable se new list banane ka concise pattern hai.

list-comprehension.pyPython
numbers = [1, 2, 3, 4, 5]
squares = [number * number for number in numbers]
print(squares)

Equivalent normal loop:

loop-version.pyPython
squares = []
for number in [1, 2, 3, 4, 5]:
    squares.append(number * number)

Try list comprehension →

Filter inside a comprehension

Ending if condition items ko filter karti hai.

filter.pyPython
numbers = range(1, 11)
evens = [number for number in numbers if number % 2 == 0]
print(evens)

Read order: expression, loop, then filter condition.

Conditional expression inside a comprehension

Transformation me two possible outputs chahiye to conditional expression expression-part me aata hai.

labels.pyPython
scores = [42, 78, 91, 35]
labels = ["Pass" if score >= 40 else "Fail" for score in scores]
print(labels)

if ... else yaha filter nahi; each input ke liye output choose kar raha hai.

Nested comprehensions

flatten.pyPython
matrix = [[1, 2], [3, 4], [5, 6]]
flat = [value for row in matrix for value in row]
print(flat)

Nested comprehension powerful hai, but multiple levels/conditions ke baad readability quickly drop ho sakti hai. Complex transformation ke liye normal loops or helper function better ho sakte hain.

Set comprehensions

Curly braces with one expression unique result set create karte hain.

set-comp.pyPython
words = ["Python", "python", "CSS", "css", "Python"]
normalized = {word.lower() for word in words}
print(normalized)

Set ordering ko semantic requirement mat samjho; set ka primary purpose uniqueness/membership hai.

Dictionary comprehensions

dict-comp.pyPython
names = ["Aman", "Riya", "Kabir"]
lengths = {name: len(name) for name in names}
print(lengths)

Key and value dono expression ho sakte hain.

Try dictionary comprehension →

Generator expressions recap

Parentheses wala comprehension-style syntax generator expression create karta hai, jo lazy hota hai.

generator-expression.pyPython
total = sum(number * number for number in range(1, 6))
print(total)

Intermediate list ki zaroorat nahi, so built-ins ke saath generator expression often clean choice hai.

Lambda functions

lambda small anonymous function expression banata hai. Syntax:

lambda.pyPython
double = lambda value: value * 2
print(double(5))

Equivalent named function:

named.pyPython
def double(value):
    return value * 2
Rule of thumb: Lambda ko short, one-expression behavior ke liye use karo, especially temporary key functions. Reusable/business logic ke liye normal def usually clearer hai.

Lambda limitations

  • Lambda body one expression hoti hai, normal statement block nahi.
  • return keyword nahi likhte; expression result automatically return hota hai.
  • Complex validation, loops, exceptions or documentation ke liye normal function better hai.
  • Meaningful named function debugging and reuse me easier hota hai.

sorted() and key functions

sorted() new sorted list return karta hai. key har item se comparison key calculate karta hai.

sorting.pyPython
students = [
    {"name": "Aman", "score": 78},
    {"name": "Riya", "score": 92},
    {"name": "Kabir", "score": 84},
]

ranked = sorted(students, key=lambda student: student["score"], reverse=True)
for student in ranked:
    print(student["name"], student["score"])

list.sort() existing list ko in-place modify karta hai; sorted() any iterable accept karke new list deta hai.

Try sorting with lambda →

operator.itemgetter() as a readable key helper

itemgetter.pyPython
from operator import itemgetter

students = [
    {"name": "Aman", "score": 78},
    {"name": "Riya", "score": 92},
]

print(sorted(students, key=itemgetter("score"), reverse=True))

Simple field lookup ke liye itemgetter() lambda ka readable alternative ho sakta hai.

map()

map(function, iterable) har item par function apply karke lazy iterator return karta hai in Python 3.

map.pyPython
numbers = [1, 2, 3, 4]
doubled = map(lambda number: number * 2, numbers)
print(list(doubled))

Simple transformations me comprehension often more readable hoti hai: [number * 2 for number in numbers].

filter()

filter(function, iterable) wo items pass karta hai jinke liye function truthy result return kare.

filter-built-in.pyPython
numbers = [1, 2, 3, 4, 5, 6]
evens = filter(lambda number: number % 2 == 0, numbers)
print(list(evens))

Again, simple case me [n for n in numbers if n % 2 == 0] often easier to read hai.

zip()

zip() multiple iterables ko position-wise combine karta hai and tuples produce karta hai.

zip.pyPython
names = ["Aman", "Riya", "Kabir"]
scores = [78, 92, 84]

for name, score in zip(names, scores):
    print(name, score)

Default zip() shortest iterable end hone par stop karta hai. Equal-length data required ho to lengths validate karo or modern Python me appropriate strict behavior consider karo.

enumerate()

Manual counter maintain karne ke bajay enumerate() index + value deta hai.

enumerate.pyPython
topics = ["HTML", "CSS", "Python"]

for position, topic in enumerate(topics, start=1):
    print(position, topic)

any() and all()

any() true hota hai agar at least one item truthy ho. all() true hota hai agar all items truthy hon. Empty iterable ke case me any([]) false and all([]) true hota hai.

any-all.pyPython
scores = [78, 92, 84]

print(any(score >= 90 for score in scores))
print(all(score >= 40 for score in scores))

Useful numeric built-ins

numeric.pyPython
numbers = [12, 5, 27, 9]

print(sum(numbers))
print(min(numbers))
print(max(numbers))
print(abs(-15))
print(round(3.14159, 2))
print(divmod(17, 5))

round() decimal formatting ka universal replacement nahi; display precision aur financial decimal arithmetic ke requirements alag ho sakte hain.

Useful object/type built-ins

object-builtins.pyPython
value = [1, 2, 3]

print(len(value))
print(type(value))
print(isinstance(value, list))
print(callable(len))
print(repr(value))

Runtime type relationship check ke liye isinstance() usually direct type(x) == SomeType se more flexible hai because inheritance ko respect karta hai.

reversed() and reverse sorting

reverse.pyPython
numbers = [10, 20, 30]
print(list(reversed(numbers)))
print(sorted(numbers, reverse=True))

reversed() traversal order reverse karta hai; sorted(..., reverse=True) sorted order descending karta hai. Dono same concept nahi hain.

min()/max() with key

best-student.pyPython
students = [
    {"name": "Aman", "score": 78},
    {"name": "Riya", "score": 92},
    {"name": "Kabir", "score": 84},
]

best = max(students, key=lambda student: student["score"])
print(best)

Full list sort karna zaroori nahi when you only need minimum or maximum item.

Combine tools without creating unreadable code

report.pyPython
students = [
    {"name": " Aman ", "score": 78},
    {"name": "Riya", "score": 92},
    {"name": " Kabir", "score": 35},
]

passed = [
    {"name": student["name"].strip(), "score": student["score"]}
    for student in students
    if student["score"] >= 40
]

for position, student in enumerate(
    sorted(passed, key=lambda item: item["score"], reverse=True),
    start=1,
):
    print(position, student["name"], student["score"])

Line breaks and helper variables readability improve karte hain. One expression me sab kuch squeeze karna goal nahi hai.

Performance perspective

  • Comprehensions CPython me equivalent manual append loops se often concise and efficient ho sakti hain, but readability first rakho.
  • Generator expressions intermediate list avoid kar sakte hain when one-pass processing sufficient ho.
  • Repeatedly sorting when only min()/max() needed ho unnecessary work hai.
  • Built-ins commonly optimized hote hain, but performance claims ko actual workload ke saath measure karo.

Common beginner mistakes

  • Every loop ko comprehension me convert kar dena, even when logic complex ho.
  • Nested comprehension ka order confuse karna.
  • Filter if aur conditional expression x if condition else y ko mix up karna.
  • Lambda me complicated business logic cram karna.
  • map()/filter() result ko list samajhna; Python 3 me ye iterators hain.
  • sorted() ko in-place sorting samajhna.
  • list.sort() ke return value ko sorted list samajhna; it returns None.
  • zip() unequal lengths silently truncate kar sakta hai — is behavior ko ignore karna.
  • all([]) false assume karna.
  • Built-in names such as list, sum, filter ko variables se shadow karna.

Beginner best practices

  • Simple transformation/filter ke liye comprehensions use karo.
  • Complex multi-step logic ke liye helper function or normal loop prefer karo.
  • Lambda ko short key/callback expressions tak limited rakho.
  • Sorting ke liye clear key functions use karo.
  • Index ke liye enumerate(), parallel iteration ke liye zip() prefer karo.
  • Boolean collections ke liye any()/all() consider karo.
  • One-pass aggregate me generator expressions useful hain.
  • Built-in function names overwrite mat karo.

Chapter checklist

  • List, set and dictionary comprehension likh sakte ho?
  • Comprehension filter aur conditional expression ka difference clear hai?
  • Generator expression vs list comprehension kab use karna hai samajh aaya?
  • Simple lambda function bana sakte ho?
  • sorted(..., key=...) se custom sorting kar sakte ho?
  • map() and filter() lazy iterators hain — clear hai?
  • zip() and enumerate() practical loops me use kar sakte ho?
  • any(), all(), min(), max(), sum() ka role clear hai?

Practice Task — Student Analytics Pipeline

BrounStack Playground me concise but readable analytics program banao.

  1. At least 5 student dictionaries banao with name, score and city.
  2. List comprehension se all names clean/strip karo.
  3. Passing students filter karo.
  4. Set comprehension se unique cities nikalo.
  5. Dictionary comprehension se name → score mapping banao.
  6. sorted() + lambda se ranking banao.
  7. enumerate(start=1) se rank numbers print karo.
  8. max() with key se topper nikalo.
  9. sum() and len() se average calculate karo.
  10. any() se check karo kya koi score 90+ hai.
  11. all() se check karo kya sab scores valid 0–100 range me hain.
  12. zip() ka ek useful example add karo.
  13. Same transformation ka one map() or filter() version compare karo.
  14. At least one complex one-liner ko intentionally normal loop/helper function me rewrite karo for readability.

Open practice starter →