0

in below code i want test zip() method. in one example i iterate in b (zip output) and the second convert b to the set.but when i convert the b to set strange thing happened. the ones that iterate in b, print it output is empty list. but when i comment the c = set(b) and print(c) the output is correct what happen and why? can you explain for me.

    l1 = range(10)
    l2 = range(10)
    b = zip(l1,l2)
    c = set(b)
    print(c)
    result = [(x,y) for x,y in b]
    print(len(result))
jpp
  • 159,742
  • 34
  • 281
  • 339
  • 1
    `zip` returns an iterator. Calling `set` on that iterator consumes it, making it empty. When the list comprehension `[(x,y) for x,y in b]` is executed, `b` is empty and you get an empty list. – Aran-Fey Mar 29 '18 at 15:40
  • thanks a lot, can you give me a reference for more study please – arash moradi Mar 29 '18 at 15:47
  • You mean about iterators? Take a look [here](https://stackoverflow.com/questions/9884132/what-exactly-are-pythons-iterator-iterable-and-iteration-protocols) – Aran-Fey Mar 29 '18 at 15:49
  • i mean for exhausted iterator – arash moradi Mar 29 '18 at 15:51
  • I don't think you'll find anything specifically about exhausted iterators. Asking for a reference about exhausted iterators is like asking for a reference about the number 4. Why should there be a reference about the number 4? 4 is a number like any other. It's not really special. You should just learn about numbers in general instead. – Aran-Fey Mar 29 '18 at 15:54

1 Answers1

1

zip is an iterator which you have exhausted.

As per the documentation, zip is equivalent to the generator function below (notice the yield statement):

def zip(*iterables):
    # zip('ABCD', 'xy') --> Ax By
    sentinel = object()
    iterators = [iter(it) for it in iterables]
    while iterators:
        result = []
        for it in iterators:
            elem = next(it, sentinel)
            if elem is sentinel:
                return
            result.append(elem)
        yield tuple(result)

You can exhaust a generator in many ways. For example, by calling list or set on it, or by applying next until it exhausts.

Since you have called set on the generator, its contents are emptied and are no longer iterable, unless they have been stored via the exhausting function.

You can find some examples and solutions in exhausted iterators - what to do about them?. In particular, itertools.tee can conveniently copy an iterator so that you can "reuse" it.

Community
  • 1
  • 1
jpp
  • 159,742
  • 34
  • 281
  • 339