You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
- From Python [docs](https://docs.python.org/3.3/library/functions.html#zip), here's an approximate implementation of zip function,
1275
+
```py
1276
+
def zip(*iterables):
1277
+
sentinel = object()
1278
+
iterators = [iter(it) for it in iterables]
1279
+
while iterators:
1280
+
result = []
1281
+
for it in iterators:
1282
+
elem = next(it, sentinel)
1283
+
if elem is sentinel:
1284
+
return
1285
+
result.append(elem)
1286
+
yield tuple(result)
1287
+
```
1288
+
- So the function takes in arbitrary number of itreable objects, adds each of their items to the `result` list by calling the `next` function on them, and stops whenever any of the iterable is exhausted.
1289
+
- The caveat here is when any iterable is exhausted, the existing elements in the `result` list are discarded. That's what happened with `3` in the `numbers_iter`.
1290
+
- The correct way to do the above using `zip` would be,
1291
+
```py
1292
+
>>> numbers = list(range(7))
1293
+
>>> numbers_iter = iter(numbers)
1294
+
>>> list(zip(first_three, numbers_iter))
1295
+
[(0, 0), (1, 1), (2, 2)]
1296
+
>>> list(zip(remaining, numbers_iter))
1297
+
[(3, 3), (4, 4), (5, 5), (6, 6)]
1298
+
```
1299
+
The first argument of zip should be the one with fewest elements.
0 commit comments