How do I create an infinite loop of binary digits?

Viewed 147

So for example: 0 10 11 100 101 110 111

And so on.

I would like to have it go infinitely, but that might not be possible. I have already tried this:

lista = [1,2,3,4,5,6,7,8,9,10]
listres = [str(bin(x))[2:].zfill(4) for x in lista]
print(listres)

And it works, but it is all one line, and also not infinite.

3 Answers

You could create a generator:

def infinite_binary():
    x = 0
    while True:
        yield str(bin(x))[2:]
        x += 1

infinite_binary_gen = infinite_binary()
while True:
    print(next(infinite_binary_gen))

Output:

0
1
10
11
100
101
110
111
1000
1001
... and so on

As mentioned in @chepner's comment you can use itertools.count(start=0, step=1) for the base generator:

from itertools import count

infinite_binary_gen = (str(bin(x))[2:] for x in count())
while True:
    print(next(infinite_binary_gen))

I would just use a while loop. This way, you could do it in 4 lines of code. Try this:

count = 1

while True:
    listres = str(bin(count))[2:].zfill(4)
    print(listres)
    count += 1

Use a loop like this instead of a list comprehension:

i = 0
while True:
    # uncomment this line to break the infinite loop:
    # if i > 10: break
    print(str(bin(i))[2:])
    i += 1

Note that zfill(4) is not needed here.

If you need to cast the result to int, use: print(int(str(bin(i))[2:]))

Related