Python append adds an element to each variable

advertisements

I'm iterating on a list and attempting to create sublists from its items. Every time I append to a variable, the value is added to every other variable that I have defined. I've stripped down the code substantially to illustrate.

item = 'things.separated.by.periods'.split('.')
list1 = list2 = []

i = item.pop(0)
print i
list1.append(i)
i = item.pop(0)
print i
list2.append(i)

print(item, list1, list2)

Returns:

things
separated
(['by', 'periods'], ['things', 'separated'], ['things', 'separated'])

What I expected:

things
separated
(['by', 'periods'], ['things'], ['separated'])

I think this might by answered here, but I'm not sure how to apply this fix to my circumstances. Thanks in advance!


The problem is the line

list1 = list2 = []

This makes list1 and list2 refer to the exact same list, so that if you append an item to one you also append it to the other. Change it to

list1 = []
list2 = []