Python Simple Code Questions

Asked 1 years ago, Updated 1 years ago, 357 views

Hello, it's a simple code, but I don't understand it well, so I'm asking.

case1=['a','b','c']
case2=['d','e','a']
result=[]
subresult=[]

for j in case2:
    for i in case1:
        subresult.append(i+j)
    result.append(subresult)

If you output the result here,

[['ad', 'bd', 'cd'], ['ad', 'bd', 'cd', 'ae', 'be', 'ce'], ['ad', 'bd', 'cd', 'ae', 'be', 'ce', 'aa', 'ba', 'ca']]

I think the above results should come out, but the following results will come out.

[['ad', 'bd', 'cd', 'ae', 'be', 'ce', 'aa', 'ba', 'ca'], ['ad', 'bd', 'cd', 'ae', 'be', 'ce', 'aa', 'ba', 'ca'], ['ad', 'bd', 'cd', 'ae', 'be', 'ce', 'aa', 'ba', 'ca']] 

I don't really understand why it's coming out like this, can anyone help me..

python

2023-03-21 00:33

1 Answers

There are three subresults in the result Even if the result is already in the result If the subresult is changed It changes (because it's the same instance) together.


2023-03-22 02:37

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.