0
Could anyone help to explain below code? why have such difference if i put "results" in different Position in a loop.
#Position1: #results=[] for i in range(2): #Position2: results=[] for j in range(3): #Position3: #results=[] results.append(i+j) print(results) Why the results in Position1,2,3 have different output?
2 Answers
+ 5
Position 1: results is created once and the sum of i and j is appended every time j is incremented => [0, 1, 2, 1, 2, 3]
Position 2: results is created anew/overridden each time i is incremented => [1, 2, 3]
Position 3: results is created anew/overridden each time j is incremented => [3]
You can play around with this code to see the difference:
https://code.sololearn.com/cOFJqVgt849j/?ref=app
- 6
<redacted>
MyIQis150 please be mindful of how to treat other users.