0

In this program I want to remove the duplicate values from the list. This is what i wrote:

list = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

def loop():
    for a in range(len(list)-1):
        for b in range(a+1,len(list)):
            if list[a] == list[b]:
                del list[a]
    print(list)  
loop()

But, it's giving me this error:

enter image description here

Can you help me?

vaultah
  • 44,105
  • 12
  • 114
  • 143
Protul
  • 95
  • 1
  • 7
  • It's because you are deleting items while you are looping through the list, create a new list with only the items you want. If you want to remove duplicates you can just do `list(set(listName))` – Keatinge Nov 13 '16 at 07:28

3 Answers3

0

If you have numpy then you can do (I renamed your list to l to avoid ambiguity):

import numpy as np 
l = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
l_no_duplicates = list( np.unique(l) )
Angus Williams
  • 2,284
  • 19
  • 21
0

The common approach to get a unique collection of items is to use a set. Sets are unordered collections of distinct objects.

list = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
newList = list(set(list))

[1, 2, 3, 5, 8, 13, 34, 21, 55, 89]

anati
  • 264
  • 2
  • 13
-1

Do something like the following:

create new_list
for item in list:
    if item not in new_list:
        add item to new_list
list = new_list

In Python:

list = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

print list
new_list = []
for item in list:
    if item not in new_list:
        new_list.append(item)
list = new_list
print list

Now run python filename.py and you will see the difference between two lists.

MiniGunnR
  • 5,590
  • 8
  • 42
  • 66