Reputation: 85
I'm trying to append a temporary list (temp) to the main list (dfl) where the temporary list changes the elements inside it each iteration of a for loop.
The code snippet is below-
for i in range(1,n+1):#n is the number of rows
for j in range(2,8):
data = driver.find_element_by_xpath("//xpath").text #Data is derived from a website element by element
temp.append(data)
dfl.append(temp)
print(dfl)
temp.clear()
Now, the print(dfl)
gets me the desired output, [[list1],[list2]]
.
But when I execute the same print(dfl)
outside the for loop, its printing out two empty lists like so [[],[]]
Where am I going wrong?
Upvotes: 0
Views: 368
Reputation: 54
because you clear it with temp.clear()
the temp in dfl is the same object as the temp.
you can try:
import copy
...
dfl.append(copy.deepcopy(temp))
Upvotes: 2
Reputation: 50899
dfl.append(temp)
doesn't append the values of temp
, it append a reference to temp
. You need to append a copy of temp
for i in range(1,n+1):#n is the number of rows
for j in range(2,8):
data = driver.find_element_by_xpath("//xpath").text #Data is derived from a website element by element
temp.append(data)
dfl.append(temp[:])
print(dfl)
temp.clear()
Upvotes: 4