-2

I'm newbie to coding and this makes me crazy. I'm trying to compare items of a list to eliminate the duplicates but it doesn't work. here results are fine:

L = [1, 2, 3]
for i in L[:]:
    for j in L[:]:
        print(L.index(i), i, L.index(j), j)

but if I change the list to this:

    L = [1, 1, 3]

it won't work. it skips some items and prints some others twice. any ideas?

  • 1
    what exactly do you want to do? not sure I understand. Maybe you want to loop over indices instead of elements here? – Banana Feb 02 '18 at 16:26
  • `index` only returns the _first_ index for a particular value – roganjosh Feb 02 '18 at 16:26
  • 2
    This seems like an [XY problem](https://meta.stackexchange.com/a/66378). What is your end goal? There's likely a better solution, perhaps using `set`s. – pault Feb 02 '18 at 16:28
  • I just want to use a loop to compare all items in list,that's all. I know there might be tons of solutions to my problem but I want to try it this way.just a simple question?How to use nested loop to compare all items of a list 2 by 2? – fardin gholami Feb 02 '18 at 16:31

2 Answers2

2

You can change it to set which ensures items are unique:

In [1]: my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0]

In [2]: my_new_list = list(set(my_list))

In [3]: my_new_list
Out[3]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Keep in mind, however, that set is unorderd data structure, which means the order may differ.

In you case you can check it this way:

In [4]: my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0]

In [5]: my_new_list = []

In [6]: for element in my_list:
   ...:     if element not in my_new_list:
   ...:         my_new_list.append(element)
   ...:         

In [7]: my_new_list
Out[7]: [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
gonczor
  • 3,994
  • 1
  • 21
  • 46
  • What if he wants to keep repeated items? – SuperStew Feb 02 '18 at 16:31
  • What do you mean? The problem is with removing duplicates. – gonczor Feb 02 '18 at 16:32
  • @A.B. Docs say it's immutable but not that it maintains any specific order. If you can prove it is other way I'll be happy to update answer and learn something new. – gonczor Feb 02 '18 at 16:38
  • Thanks for your help.It helped a lot. but actually I was going to practice loops and kind of solve the problem by my own way.not by using some other functions. for example I know there is a "max" built in function but what if I want to use my code to find that?anyways all I was asking was just how to address items in list two time with duplicate items – fardin gholami Feb 02 '18 at 16:41
  • @gonczor ah, you are correct. – A.B. Feb 02 '18 at 16:44
0

Remove duplicates in list (Note use this if order of elements is not important for you):

L = [1, 1, 3]
print(list(set(L)))

Outputs:

[1, 3]
Austin
  • 25,759
  • 4
  • 25
  • 48