ARNAV RAMKRISHNAN ARNAV RAMKRISHNAN - 1 month ago 12
Python Question

Python list changing value outside the loop. Absolutely baffling

So, I was implementing a simple do-while in python. Everything goes as expected, except the moment I exit the while loop, the appended list inexplicably changes value.

I included print statements all over the place. The list is correct till the very last statement. Then the code doesn't even enters the while loop again, but somehow the list value changes?!?

Here's the code-

condition = True
while condition == True:
bindigits.clear()
for i in range(0, 7):
if data[a][0] % 2 == 0:
bindigits.append(0)
if data[a][0] % 2 == 1:
bindigits.append(1)
a = a+1

if bindigits == [0, 0, 0, 0, 0, 0, 0]:
condition = False
else:
binletters.append(bindigits)
print('binletters is now', binletters)
print('checking while loop condition')
print('exited while loop')

print('binletters is now', binletters)


Here's the output (from where it goes wrong):

Binletters is now [[1,1,1,0,0,1,1],[1,0,1,1,0,0,1]... (relevant values) ]

Checking while loop condition

Condition false

Exited while loop

Binletters is now [[0,0,0,0,0,0,0],[0,0,0,0,0,0,0].. (all zeros)]

Tried everything. Gave up. Please help!!

Answer Source

you actually add every time a bindigits cleared (i guess clear update it with all zeros). What you need to do is after updating binletters with append to create new bindigits instance. you can add before the clear method bindigits=[] so it would be new instance.

Also what @venky_ wrote will work from the same reason.