Home > other >  Why is there a difference in the results of both the for loops?
Why is there a difference in the results of both the for loops?

Time:01-25

Both of the for loops are the exact same but i dont understand why the first for loop isnt working.

t = [[1,0],[2,0]]
z =  [[1,0],[2,0]]
for i in t:
    i = [x for x in i if x!=0]
for i in range(len(z)):
    z[i] = [x for x in z[i] if x!=0]
print(t)
print(z)

Output:

[[1, 0], [2, 0]]

[[1], [2]]

CodePudding user response:

The first loop is just overwriting the temporary variable i rather than writing that data back to the array.

for i in t:
    # saves data back to loop variable i 
    i = [x for x in i if x!=0]
for i in range(len(z)):
    # saves data to this index in array z
    z[i] = [x for x in z[i] if x!=0]

When you assign a new value to i, you don't change the data that i originally referred to (the data in the array t). Instead, you cause i to refer to the new data. The array remains unchanged unless you change it explicitly - like you do in the second loop.

  •  Tags:  
  • Related