2

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
  • Since you need infinite items, you can not store those in list. Do you need your programs to infinitely just print the binary numbers ? Commented Jan 6, 2021 at 21:07
  • Use a generator function. Commented Jan 6, 2021 at 21:07
  • while True: digit = random.choice([0,1]) Commented Jan 6, 2021 at 21:27

3 Answers 3

3

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))
Sign up to request clarification or add additional context in comments.

1 Comment

More simply, itertools.count already provides the base generator needed. infinite_binary_gen = (str(bin(x))[2:] for x in count()).
0

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:]))

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.