0

This is really annoying. I create a sublist with elements from the original list. Then when I mutate the sublist the original list gets mutated too even though they SHOULD be in different objects in different memory locations.

data = [['male', 'weak'], ['female', 'weak'], ['female', 'strong']]
subdata = []
for i in data:
    if(i[1] == 'weak'):
        subdata.append(i)
subdata[0].pop(0)
print(subdata)
print(data)
Jerrold110
  • 191
  • 1
  • 4

1 Answers1

1

Copying your sublist with [:] works:

data = [['male', 'weak'], ['female', 'weak'], ['female', 'strong']]
subdata = []
for i in data:
    if(i[1] == 'weak'):
        subdata.append(i[:])
subdata[0].pop(0)
print(subdata)
print(data)

Output:

[['weak'], ['female', 'weak']]
[['male', 'weak'], ['female', 'weak'], ['female', 'strong']]

Your original output:

['weak'], ['female', 'weak']]
[['weak'], ['female', 'weak'], ['female', 'strong']]

In case your sublist would contain a more deeply nested list use copy.deepcopy():

data = [['male', 'weak'], ['female', 'weak'], ['female', 'strong']]
subdata = []
for i in data:
    if(i[1] == 'weak'):
        subdata.append(copy.deepcopy(i))
subdata[0].pop(0)
print(subdata)
print(data)

Output:

[['weak'], ['female', 'weak']]
[['male', 'weak'], ['female', 'weak'], ['female', 'strong']]
Mike Müller
  • 82,630
  • 20
  • 166
  • 161