0

I have a piece of code which is doing a different thing to what I feel it should. This is a module I built to test this problem in a larger piece of code:

class plant:
    def __init__ (self, param):
        self.param = param
plants = []
for i in range(10):
    plants.append(plant(10))
plant1 = plants[0]
plants1 = plants
print(len(plants))
for i in plants:
    print("Item removed")
    plants.remove(i)
print(plant1)
print(len(plants))
print(len(plants1))

This produces the output as

10

Item removed

Item removed

Item removed

Item removed

Item removed

<__main__.plant object at 0x02780F30>

<__main__.plant object at 0x02780F30>

5
5

Why does it remove the items from plants1 as well but not from plant1? And how do I stop it doing that?

jww
  • 97,681
  • 90
  • 411
  • 885
Sacasco
  • 11
  • 2

1 Answers1

0

Therelevant part of your code is here:

plant1 = plants[0]
plants1 = plants

plant1 now refers to tthe object at the first index of plants and this will still point to that same object even if it's removed from plants. You still only have one object, rather than two duplicates.

Similarly, plants and plants1 refer to the same list. You have not duplicated your list by assigning one to another. Thus anything you do to plants1 you are also tacitly doing to plants.

Really, you need to look at this question on duplicating a list.

Community
  • 1
  • 1
deau
  • 1,193
  • 1
  • 9
  • 14