I am trying to print all the possible enumerations of a list for three variables. For example if my input is:
x = 1
y = 1
z = 1
I want the output to be like:
[[0, 0, 0], [0, 0, 1], [0, 1, 0], [1, 0, 0], [1, 1, 0], [1, 0, 1], [0, 1, 1], [1, 1, 1]]
If any of the x,y,z variables are higher than 1, it would enumerate all the integers from 0 to the variable value. For example, if x=3 then 0, 1, 2, or 3 would be possible in the first slot of the 3-element lists.
Right now I am creating the list comprehension like this:
output = [ [x,y,z] for x,y,z in range(x,y,z)]
I think something is wrong with the range function?
Using enumerate inside a list comprehension returns a list that contains tuples consisting of a index value and the corresponding element. For example, using enumerate inside a list comprehension using the list, ["a", "b", "c"] , returns [(0, "a"), (1, "b"), (2, "c")] .
Now, on a practical note: you build up a list with two square brackets; Inside these brackets, you'll use commas to separate your values. You can then assign your list to a variable. The values that you put in a Python list can be of any data type, even lists!
extend to extend the list by multiple values from any kind of iterable, being it another list or any other thing that provides a sequence of values. So you can use list. append() to append a single value, and list. extend() to append multiple values.
2 List Comprehension. This has two drawbacks: You can only look for one value at a time. It only returns the index of the first occurrence of a value; if there are duplicates, you won't know about them.
Complementary to the solutions using product
, you could also use a triple list comprehension.
>>> x, y, z = 1, 2, 3
>>> [(a, b, c) for a in range(x+1) for b in range(y+1) for c in range(z+1)]
[(0, 0, 0),
(0, 0, 1),
(0, 0, 2),
(some more),
(1, 2, 2),
(1, 2, 3)]
The +1
is necessary since range
does not include the upper bound.
If you want the output to be a list of lists, you can just do [[a, b, c] for ...]
.
Note, however, that this will obviously only work is you always have three variables (x
, y
, z
), while product
would work with an arbitrary number of lists/upper limits.
You could use the product()
function from itertools
as follows:
from itertools import product
answer = list(list(x) for x in product([0, 1], repeat=3))
print(answer)
Output
[[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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With