0

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?

user3483203
  • 50,081
  • 9
  • 65
  • 94
He Sun
  • 3
  • 2
  • Possible duplicate of [List of lists changes reflected across sublists unexpectedly](https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly) – user3483203 Jul 06 '18 at 21:57
  • You are appending the same list each time. – user3483203 Jul 06 '18 at 21:58

2 Answers2

1

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)]
user3483203
  • 50,081
  • 9
  • 65
  • 94
0

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]]
blhsing
  • 91,368
  • 6
  • 71
  • 106