Reputation: 3
I'm learning Python's nested loops but couldn't use nested loops to fill a list with the combinations. So far I have
for i in range(3):
for j in range(3):
paths = [i,j]
print paths
When this prints I get:
[0, 0]
[0, 1]
[0, 2]
[1, 0]
[1, 1]
[1, 2]
[2, 0]
[2, 1]
[2, 2]
Which is a list of the possible combinations but if I try an extra for-loop to index them it doesn't seem to work and only gives the first element. I'm trying to get an array in the form:
Array = [[0,0], [0,1]... [2,2]]
where I can index said array and get Array[0] == [0,0]
and so on.
Any hints on how to do this? I've tried for-loops and using the append function neither giving me the results I wanted.
Upvotes: 0
Views: 21958
Reputation: 31339
I like list comprehension!
print [[x, y] for x in range(3) for y in range(3)]
But it creates three lists (the iterated two stay in memory) in python 2.7 which is the common one nowdays.
If you're using big values try this:
print [[x, y] for x in xrange(3) for y in xrange(3)]
which uses Generators :)
Upvotes: 4
Reputation:
The easiest way to do this is to use itertools.product
:
>>> from itertools import product
>>> combos = [list(x) for x in product(range(3), repeat=2)]
>>> combos
[[0, 0], [0, 1], [0, 2], [1, 0], [1, 1], [1, 2], [2, 0], [2, 1], [2, 2]]
>>> combos[0]
[0, 0]
>>> combos[1]
[0, 1]
>>> combos[8]
[2, 2]
>>>
Note that this solution is also very flexible. For example, if you want to find the combinations of the numbers one through five taken three at a time, all you need to do is change the numbers given to range
and repeat
:
combos = [list(x) for x in product(range(6), repeat=3)]
# ^ ^
Upvotes: 1
Reputation: 122326
You can append the lists to the result:
result = []
for i in range(3):
for j in range(3):
paths = [i,j]
result.append(paths)
print paths
print result
This says: create a result list []
and append the paths
value to it at each step. You'll then have a list of lists and you can access the first element as result[0]
(which is indeed [0, 0]
).
Upvotes: 2
Reputation: 35891
You can achieve it using itertools
:
>>> import itertools
>>> list(itertools.product(range(3), range(3)))
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
If you really need lists instead of tuples:
>>> import itertools
>>> list(itertools.product(range(3), range(3)))
>>> [list(t) for t in itertools.product(range(3), range(3))]
[0, 0], [0, 1], [0, 2], [1, 0], [1, 1], [1, 2], [2, 0], [2, 1], [2, 2]]
Upvotes: 0