1 | initial version |
Here is an easy way to accomplish what you want:
sage: A = [[1], [2]]
sage: B = ['a', 'b']
sage: [[x + [y] for x in A] for y in B]
[[[1, 'a'], [2, 'a']], [[1, 'b'], [2, 'b']]]
Or if you like:
C = []
for x in A:
for y in B:
C.append(x+[y])
I think that the problem with your original code is that you are looping over a list while also modifying that list, which is why working with a copy helps. Note also that code like a.append(1)
will change the original list a
, and that can be confusing.
for x in A:
x.append(2)
modifies each list in A, while
for x in A:
x + [2]
leaves A unchanged.
2 | No.2 Revision |
Here is an easy way to accomplish what you want:
sage: A = [[1], [2]]
sage: B = ['a', 'b']
sage: [[x + [y] for x in A] for y in B]
[[[1, 'a'], [2, 'a']], [[1, 'b'], [2, 'b']]]
Or if you like:
C = []
for x in A:
for y in B:
C.append(x+[y])
I think that the problem with your original code is that you are looping over a list while also modifying that list, which is why working with a copy helps. Note also that code like a.append(1)
will change the original list a
, and that can be confusing.
for x in A:
x.append(2)
modifies each list in A, while
for x in A:
x + [2]
leaves A unchanged.
Edit: this looks like a job for itertools
: https://docs.python.org/3/library/itertools.html. Create multiple lists A = [1, 2]
, B = ['a', 'b']
, C = ['o', 'p']
and do
from itertools import product
product(A, B, C)
or to get something more explicit:
list(product(A, B, C))
(The product
function gives the Cartesian product of the inputs.) If you don't want multiple lists, create a single list C = [[1, 2], ['a', 'b'], ['o', 'p']]
and then do product(*C)
. (Or if you have your two lists A
and B
as in the comments, you can do C = A + B
.)
3 | No.3 Revision |
Here is an easy way to accomplish what you want:
sage: A = [[1], [2]]
sage: B = ['a', 'b']
sage: [[x + [y] for x in A] for y in B]
[[[1, 'a'], [2, 'a']], [[1, 'b'], [2, 'b']]]
Or if you like:
C = []
for x in A:
for y in B:
C.append(x+[y])
I think that the problem with your original code is that you are looping over a list while also modifying that list, which is why working with a copy helps. Note also that code like a.append(1)
will change the original list a
, and that can be confusing.
for x in A:
x.append(2)
modifies each list in A, while
for x in A:
x + [2]
leaves A unchanged.
Edit: this looks like a job for itertools
: https://docs.python.org/3/library/itertools.html. Create multiple lists A = [1, 2]
, B = ['a', 'b']
, C = ['o', 'p']
and do
from itertools import product
product(A, B, C)
or to get something more explicit:
list(product(A, B, C))
(The product
function gives the Cartesian product of the inputs.) If you don't want multiple lists, create a single list C = [[1, 2], ['a', 'b'], ['o', 'p']]
and then do product(*C)
. (Or if you have your two lists A
and B
as in the comments, you can replace A
with A = [x[0] for x in A]
and do C = A + B
.)