Python Forum

Full Version: How to make this function general to create binary numbers? (many nested for loops)
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
As you can notice, this function is designed to create binary numbers in order into a list of lists. It works for 4 digits and each for loop is responsible for modifying a certain position.

I would like to modify it so I can use it for any number of digits, but I haven't found a way to do it as I have to add a for loop every time I want to add a digit.

Thank you so much for your help.

def Binarynum():
    lista=[];
    for i in range(2):
        for j in range(2):
            for k in range(2): 
                for l in range(2):
                    lista.append([i,j,k,l]);
    return lista;

lista=Binarynum();
Do not use a semicolon in Python code - it isn't used at the end of every line
You could use the product function from itertools.

>>> from itertools import product
>>> list(product([0, 1], repeat=4))
[(0, 0, 0, 0), (0, 0, 0, 1), (0, 0, 1, 0), (0, 0, 1, 1), (0, 1, 0, 0), (0, 1, 0, 1), (0, 1, 1, 0), (0, 1, 1, 1), (1, 0, 0, 0), (1, 0, 0, 1), (1, 0, 1, 0), (1, 0, 1, 1), (1, 1, 0, 0), (1, 1, 0, 1), (1, 1, 1, 0), (1, 1, 1, 1)]
Just change the repeat value.
(Jun-23-2020, 03:51 PM)pyzyx3qwerty Wrote: [ -> ]Do not use a semicolon in Python code - it isn't used at the end of every line
I know, I just prefer to do it because every other language I code in, requires it. So I do it anyway.
How about a function that converts positive integers to lists of bits.
def binary(number):
    bits = []
    while number != 0:
        bits.insert(0, number % 2)
        number = number >> 1
    return bits
If you want to pad to some fixed length.
def binary(number, pad=0):
    bits = []
    while number != 0:
        bits.insert(0, number % 2)
        number = number >> 1
    while len(bits) < pad:
        bits.insert(0, 0)
    return bits
You could also use bin() and a list comprehension:
def binary(number, pad=0):
    return [1 if bit == '1' else 0 for bit in bin(number)[2:]]