weasel
weasel

Reputation: 574

itertools count with lists

I want to pass the itertools.count element as a list index, but it results in this error:

TypeError: list indices must be integers or slices, not itertools.count

Trying int(counter) does not work either, resulting in

TypeError: int() argument must be a string, a bytes-like object or a number, not 'itertools.count'

from itertools import count

index = count()
l = [5,6,7,8,9,0]

while True:
    print(l[int(index)])

How can I pass the count as the list index?

Upvotes: 2

Views: 905

Answers (1)

finefoot
finefoot

Reputation: 11232

You can use next to get the next element from the counter.

from itertools import count

index = count()
l = [5, 6, 7, 8, 9, 0]

while True:
    print(l[next(index)])

But the way your loop is currently structured, this will eventually result in an IndexError when the counter has reached 6, since your list only has 6 elements.

The output will look like this:

5
6
7
8
9
0
Traceback (most recent call last):
  File "test.py", line 7, in <module>
    print(l[next(index)])
IndexError: list index out of range

If you just want to print the elements of the list, you can do this with Python much easier like this:

for element in l:
    print(element)

Upvotes: 3

Related Questions