๐ Python enumerate() and zip() โ Cleaner Loop Patterns
enumerate() adds automatic counters to loops; zip() iterates multiple sequences together. Both eliminate messy manual indexing.
zip() with dict() is one of Python's most useful patterns for building mappings from parallel data.
๐ป Code Example:
# 1. enumerate() โ no more manual counter courses = ['Python', 'AI', 'DevOps', 'Testing'] # Old way (ugly) count = 0 for course in courses: print(count, course) count += 1 # Better with enumerate for idx, course in enumerate(courses, start=1): # start=1 to begin at 1 print(f"{idx}. {course}") # 2. zip() โ combine two lists students = ['santoshtvk', 'dhruv', 'tvk'] scores = [95, 88, 72] for student, score in zip(students, scores): print(f"{student}: {score}/100") # 3. zip() to create a dict pairs = dict(zip(students, scores)) print(pairs) # {'santoshtvk': 95, 'dhruv': 88, 'tvk': 72} # 4. zip() with unequal lengths โ stops at shortest names = ['Alice', 'Bob', 'Charlie'] ages = [25, 30] for name, age in zip(names, ages): print(name, age) # Only 2 pairs โ Charlie is ignored # Use itertools.zip_longest to fill missing values from itertools import zip_longest for name, age in zip_longest(names, ages, fillvalue='N/A'): print(name, age)
| Concept | Key Takeaway |
|---|---|
| enumerate(iterable, start=0) | Adds index counter to any loop |
| zip(a, b, c) | Parallel iteration of multiple sequences |
| zip_longest(a, b) | Like zip but goes to the longest sequence |
| dict(zip(keys, values)) | Clean way to build a dict from two lists |
Keep exploring and happy coding! ๐