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
51.3k10 gold badges72 silver badges104 bronze badges
asked Jul 6, 2018 at 21:53
2

2 Answers 2

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)]
answered Jul 6, 2018 at 22:02
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]]
answered Jul 6, 2018 at 21:56

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.