1

I'm trying to check the contents of a list for duplicates by storing the list in a second variable and removing one item from the list and then checking if there is still a copy of that item in the list. Here's what I've got:

disposableList = list
for i in disposableList:
    disposableList.remove(i)
    if i in disposableList:
        end = True

The problem is when it removes i from disposableList it also removes it from List. Is there a way to do this without effecting the original list?

Adam
  • 31
  • 5

2 Answers2

1

Is there a reason why you don't want to use the built-in list function list.count(item)? Imagine you have the following setup:

a = [1,2,3,4,4,5,5,5]
for i in a:
    if a.count(i) > 1:
        print("The list contains a duplicate:", i)

Or even better, if you are trying to create a list with no duplicates, use the built-in set type:

a = [1,2,3,4,4,5,5,5]
b = set(a)
print(b)

This will output "{1, 2, 3, 4, 5}"

As noted in the comments, if you still really really want to copy a list for some reason, use b=a.copy() (b=a is just a reference from b to a, if both are lists. This is why changing something in one changes it in the other.)

daviewales
  • 2,144
  • 21
  • 30
0

The first thing I would like to point out is your use of the variable name list. This is a dangerous variable name to use because list is actually a function within python, and if you type it in on python, you will notice it will turn purple. Once you have assigned the name list to a variable, you can no longer use that function's features. For the purposes of my explanation, I will be using the name my_list.

Also, the disposableList = my_list does not create a copy of the list that you are using. It just stores the original list under a new variable name.

You will find that the use of a for loop to replace the disposableList = my_list will work much better in that it will loop through the original list and place each item in a new list.

I also recommend the use of the break function as you can exit out of the loop and continue the code once certain requirements have been found.

Here is a code I have worked on for you:

my_list = [1,2,3,4,5,5]
disposableList = []
for i in my_list:
    disposableList.append(i)
for i in my_list:
    disposableList.remove(i)
    if i in disposableList:
        break

Good luck!

Jordan.