Python zip() और enumerate()
In this page:
zip(iterable1, iterable2)
enumerate(iterable, start=0)
for index, item in enumerate(iterable):
# body
zip() Function
zip(list1, list2, ...), कई iterables के corresponding elements को tuples में जोड़ता है, और सबसे छोटे input के खत्म होते ही रुक जाता है।
यह दो related lists, जैसे names और उनके corresponding scores, पर lockstep में loop करने का standard तरीका है, बिना दोनों में manually index किए।
उदाहरण: The zip() Function
names = ["Alex", "Sam"]
scores = [90, 80]
for name, score in zip(names, scores): # pairs elements from both lists together
print(name, score)
Lists को Unzip करना
एक और zip() call के अंदर किसी zipped result के आगे * लगाना उसे वापस अलग-अलग lists में unzip कर देता है, paired tuples को अलग-अलग कर देता है -- असल में zip() अपने ही operation को उलट देता है, यह एक genuinely उपयोगी लेकिन अक्सर नज़रअंदाज़ किया जाने वाला trick है।
उदाहरण: Unzipping Lists
pairs = [(1, "a"), (2, "b")]
numbers, letters = zip(*pairs) # * unzips the pairs back into separate tuples
print(numbers, letters)
enumerate() Function
enumerate(iterable) किसी sequence को इस तरह wrap करता है कि उस पर loop करने से automatically (index, value) pairs मिलते हैं, जो हाथ से loop के अंदर बढ़ाए जाने वाले एक अलग counter variable को maintain करने वाले error-prone manual pattern की जगह लेता है।
उदाहरण: The enumerate() Function
fruits = ["apple", "banana"]
for index, fruit in enumerate(fruits): # yields (index, value) pairs automatically
print(index, fruit)
Custom Starting Index
enumerate(iterable, start=1) में एक start value पास करने से index count default 0 की बजाय उस number से शुरू होता है, जो तब उपयोगी है जब आप चाहते हैं कि 1-based numbering उसी तरह मैच करे जैसे output असल में किसी व्यक्ति को दिखाया जाएगा।
उदाहरण: Custom Starting Index
fruits = ["apple", "banana"]
for index, fruit in enumerate(fruits, start=1): # index counting begins at 1 instead of 0
print(index, fruit)
zip() और enumerate() को मिलाना
enumerate(zip(list1, list2)) की तरह enumerate() के अंदर zip() को nest करना आपको कई paired lists में loop करते हुए हर pair के लिए एक running index भी track करने देता है -- जब आपको position और paired values दोनों एक साथ चाहिए हों तो दोनों patterns को मिलाना।
उदाहरण: Combining zip() and enumerate()
names = ["Alex", "Sam"]
scores = [90, 80]
for i, (name, score) in enumerate(zip(names, scores)): # index plus paired values together
print(i, name, score)
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