I have written a python code, to solve a puzzle. It was not working as expected. So while debugging I saw something very weird. Row is a list of lists. The append 1 to single row[n]
appends to all lists inside row!
def trap( height):
row = []
for index, i in enumerate(height):
if i == 0 and len(row) == 0:
continue
else:
if(i > len(row)):#time for a new row
#to old rows append 0 below
for j in range(0, len(row)):
row[j].append(0)
row = row + [[0]] * (i - len(row))
else:
for j in range(0,i):
row[j].append(0)
#PROBLEMATIC CODE START
for jo in range(i,len(row)):
if(index == 1):
print("jays are",row)
print("jo is",jo, row[jo])
row[jo].append(1)
#PROBLEMATIC CODE END (I GUESS?)
print(row) #print this, it gives an idea
trap([2,0])
When I try this independently, it works fine, see:
row = [[0],[0]]
index = 1
for jo in range(0,len(row)):
if(index == 1):
print("jays are",row)
print("jo is",jo, row[jo])
row[jo].append(1)
print(row)
The problematic code has been marked in the python as comment #PROBLEMATIC CODE START
and #PROBLEMATIC CODE END
. Call the trap()
with [2,0]
row variable should be [[0,1],[0,1]]
but row variable is coming [[0,1,1],[0,1,1]]
I have been at this for many hours! I just don't understand why does .append()
appends to all the lists inside row, but when I try the smaller code it works. Please help me and guide me