I don't know if I miss something here but don't understand why does the below list changes after using append() function. First I send a list(which contains lists) to 2 different functions.
First function just returns a random list in all non-empty lists. Second function returns a random list that if the current list(which is the one returned from the first function)'s last element lower than the other list in state
or if the list is empty.
import random
def fooOne(state):
lst = [x for x in state if len(x) > 0]
return random.choice(lst)
def fooTwo(state,current):
lst2 = [x for x in state if len(x) == 0 or x[-1] > current[-1]]
return random.choice(lst2)
state = [[3, 2, 1],
[],
[]]
cur = fooOne(state)
temp = fooTwo(state,cur)
print("State before append(): {}".format(state))
temp.append(cur.pop())
print("State after append(): {}".format(state))
Both functions returns different lists. I assign these lists to two different variables called cur
and temp
. So both cur
and temp
are also lists.
After temp.append(cur.pop())
line, original state
list changes. It'll changes like I used that line on the original list. But I'm making this operation on two different lists.
Output:
State before append(): [[3, 2, 1], [], []]
State after append(): [[3, 2], [], [1]]
Why does the original list changes while I'm using append() on another list? These lists are just some parts of the original list, why modifying them(while assigning them to new variables) affects the original list?