Andre Müller writes: > I'm a fan of infinite sequences. Try out itertools.islice. > You should not underestimate this very important module. > > Please read also the documentation: > https://docs.python.org/3.6/library/itertools.html > > from itertools import islice > > iterable = range(10000000000) > # since Python 3 range is a lazy evaluated object > # using this just as a dummy > # if you're using legacy Python (2.x), then use the xrange function for it > # or you'll get a memory error > > max_count = 10 > step = 1 > > for i, element in enumerate(islice(iterable, 0, max_count, step), start=1): > print(i, element)
I like to test this kind of thing with iter("abracadabra") and look at the remaining elements, just to be sure that they are still there. from itertools import islice s = iter("abracadabra") for i, element in enumerate(islice(s, 3)): print(i, element) print(''.join(s)) Prints this: 0 a 1 b 2 r acadabra One can do a similar check with iter(range(1000)). The range object itself does not change when its elements are accessed. -- https://mail.python.org/mailman/listinfo/python-list