0

I am using Python 3.6 I have a list:

listA = [1,2,3,1,2,4]

I am trying to remove the repetitive items from the list, so the final list will be

listA = [3,4]

After I loop once and remove 1s from the list using pop, my loop automatically advances to 3, instead of 2. To avoid this, I used following logic:

ListB= ListA
ListA.clear()
ListA = ListB

but once I clear ListA, the other list ListB is also getting cleared automatically. How can I avoid this or solve this issue?

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
user1552698
  • 577
  • 3
  • 9
  • 24
  • 1
    Make a copy: `ListB = ListA.copy()` or `ListB = list(ListA)` or `ListB = ListA[:]`. Otherwise `ListB` and `ListA` refer to the same object. – Paul Panzer Mar 11 '17 at 07:59
  • 1
    `ListA` isn't the list, it is a *name* for the list. `ListB = ListA` means `ListB` is another name for the same list. – Peter Wood Mar 11 '17 at 08:02

2 Answers2

2

Objects in Python are stored by reference,which means you didn't assign the value of ListA to ListB, but a pointer to the object.You can use is operator to test if two objects have the same address in memory.

Sequences can be copied by slicing so you can use this to copy a list:

b = a[:]

Also you can use

b = list(a)

Or you can use copy() module:

from copy import copy
b = copy(a)

See more details from How do I copy an object in Python?

McGrady
  • 10,869
  • 13
  • 47
  • 69
-1

Names of lists in python are actually just references so your new list is a reference to the same list. To actually make a new list you can use

ListB = list(ListA)
Teddy Ort
  • 756
  • 6
  • 7