I tried encoding groups of information (temp1
) to a list (temp2
) using a script and noticed that all elements of temp2
are the same and is the last value of temp1
when I did this:
if __name__ == '__main__':
temp1 = []
temp2 = []
x = ''
for i in range(0, 10):
for j in range(0, 10):
x = str(input(f'Data {j + 1} of {i + 1}: '))
temp1.append(x)
temp2.append(temp1)
temp1.clear()
print(temp1)
For explanation purposes, say I have three groups, and each group as three elements. What I am expecting is [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']]
. However, the list that I get is [['g', 'h', 'i'], ['g', 'h', 'i'], ['g', 'h', 'i']]
.
But when I used a function that returns a list, it works as intended.
def foo(lb: int, ub: int) -> list:
temp = []
y = ''
for i in (lb, ub):
y = str(input('Input: '))
temp.append(y)
return temp
if __name__ == '__main__':
temp2 = []
for j in range(0, 3):
temp2.append(foo(0, 3))
print(temp2)
Can I ask why this happens?