Trying to print multiple text in same line with append method but outputs are different

Viewed 181

Trying to print possible number combinations in single line as list but the list have wrong output. My output is like this:

[[1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1]]

When it should be like this:

[0, 0, 0]
[0, 0, 1]
[0, 1, 0]
[0, 1, 1]
[1, 0, 0]
[1, 0, 1]
[1, 1, 0]
[1, 1, 1]

My code is

if __name__ == '__main__':
    x = 1
    y = 1
    z = 1 
kordinat = ["x","y","z"]
result = []
for xx in range(x+1):
    kordinat[0] = xx
    for yy in range(y+1):
        kordinat[1] = yy
        for zz in range(z+1):
            kordinat[2]= zz
            print(kordinat)
            result.append(kordinat)
print(result)
4 Answers

You should take itertools.product():

from itertools import product

result = list(product(range(2), repeat=3))
print(result)
# [(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)]

EDIT: This does not explain, why you end up having a list full of [1, 1, 1] elements. The reason can be found here. Through all your iterations, you work with a list called koordinat. When you append this to your overall list result, you append a reference to the very same object all the time. So you will have a list full of references to the same list koordinat. So changing koordinat to [1, 1, 1] in the last iteration, will change all references in your result list to this value as well. This can best be seen, when you print result after each append()

change this line:

result.append(kordinat)

to

result.append(kordinat.copy())

list is passed or assigned as reference so if you change the value it'll change everywhere.

To print elements of list in new line use pprint as below,

>>> from pprint import pprint as pp
>>> pp(result)
[[1, 1, 1],
 [1, 1, 1],
 [1, 1, 1],
 [1, 1, 1],
 [1, 1, 1],
 [1, 1, 1],
 [1, 1, 1],
 [1, 1, 1]]

Edit-1:

Assuming, you are trying to find the binary numbers of the sequence. In your example, it is from 0-7(1-byte or 8-bits).

Try this,

>>> result = [[int(j) for j in "{0:03b}".format(i)] for i in range(8)]
>>> pp(result)
[[0, 0, 0],
 [0, 0, 1],
 [0, 1, 0],
 [0, 1, 1],
 [1, 0, 0],
 [1, 0, 1],
 [1, 1, 0],
 [1, 1, 1]]

If you want all the possible combinations of 0,1 of size 3, use combinations from itertools and call it as combinations([0,1],3). This will give you all the possible combinations you are expecting

Related