see the code below:
a=[1,2,3,4]
m=[0,0]
q=[]
for n in a:
m[0]=n
for n in a:
m[1]=n
q.append(m)
print(q)
the desired output should be:
[[1, 1], [1, 2], [1, 3], [1, 4], [2, 1], [2, 2], [2, 3], [2, 4], [3, 1], [3, 2], [3, 3], [3, 4], [4, 1], [4, 2], [4, 3], [4, 4]]
but instead the output is:
[[4, 4], [4, 4], [4, 4], [4, 4], [4, 4], [4, 4], [4, 4], [4, 4], [4, 4], [4, 4], [4, 4], [4, 4], [4, 4], [4, 4], [4, 4], [4, 4]]
any thoughts why?
-
Possible duplicate of List of lists changes reflected across sublists unexpectedlyuser3483203– user34832032018年07月06日 21:57:39 +00:00Commented Jul 6, 2018 at 21:57
-
You are appending the same list each time.user3483203– user34832032018年07月06日 21:58:02 +00:00Commented Jul 6, 2018 at 21:58
2 Answers 2
You are appending the same list to q
each time, so the changes will effect every sublist in q
. However, there is a much easier way to do this using a list comprehension:
q = [[i, j] for i in a for j in a]
Output:
[[1, 1], [1, 2], [1, 3], [1, 4], [2, 1], [2, 2], [2, 3], [2, 4], [3, 1], [3, 2], [3, 3], [3, 4], [4, 1], [4, 2], [4, 3], [4, 4]]
Or using itertools
q = list(itertools.product(a, repeat=2))
Output:
[(1, 1), (1, 2), (1, 3), (1, 4), (2, 1), (2, 2), (2, 3), (2, 4), (3, 1), (3, 2), (3, 3), (3, 4), (4, 1), (4, 2), (4, 3), (4, 4)]
In python lists are stored as references in variables, so altering m
in each iteration affects all m
references you appended to the q
list.
Instead, make a copy of m
with m[:]
before you append:
a=[1,2,3,4]
m=[0,0]
q=[]
for n in a:
m[0]=n
for n in a:
m[1]=n
q.append(m[:])
print(q)
This outputs:
[[1, 1], [1, 2], [1, 3], [1, 4], [2, 1], [2, 2], [2, 3], [2, 4], [3, 1], [3, 2], [3, 3], [3, 4], [4, 1], [4, 2], [4, 3], [4, 4]]
Explore related questions
See similar questions with these tags.