2

I am trying to remove the repeated elements from a list:

li = [11, 11, 2, 3, 4]

I am trying in these ways:

Way 1:

li = [x for x in li if x!=11]

Way 2:

for x in range(0,len(li)):
    if x==11:
        li.remove(x)

Are there any built-in functions to do this job?

ni8mr
  • 1,725
  • 3
  • 31
  • 58
  • 1
    You say "remove the repeated elements from a list", but your first code removes all number 11s instead, and your second code won't change your list (because `x` is looping from 0 to `len(l1)-1` and that will never be 11 in your case). What output are you expecting? – DSM Nov 08 '14 at 16:11
  • Try this question: http://stackoverflow.com/q/7961363/3853289 – TheDarkTurtle Nov 08 '14 at 16:13
  • My question is about removing all the repeated element '11',that is, there will be no element "11" after operation. – ni8mr Nov 08 '14 at 16:15

1 Answers1

3

Edit:

I'm sorry, I misread your question originally.

What you really want is collections.Counter and a list comprehension:

>>> from collections import Counter
>>> li= [11, 11, 2, 3, 4]
>>> [k for k, v in Counter(li).iteritems() if v == 1]
[3, 2, 4]
>>>

This will only keep the items that appear exactly once in the list.


If order does not matter, then you can simply use set:

>>> li = [11, 11, 2, 3, 4]
>>> list(set(li))
[3, 2, 11, 4]
>>>

Otherwise, you can use the .fromkeys method of collections.OrderedDict:

>>> from collections import OrderedDict
>>> li= [11, 11, 2, 3, 4]
>>> list(OrderedDict.fromkeys(li))
[11, 2, 3, 4]
>>>
  • wow, great. thank you. I have almost forget about set(). and +1 for the collections.OrderedDict() method.But my question is about removing all repeated element. That is, all "11". – ni8mr Nov 08 '14 at 16:12
  • I'm not sure that either of these will give the OP what he wants, but it's hard to be sure because neither of the OP's codes seem to achieve what he says he wants. – DSM Nov 08 '14 at 16:12
  • +1 for using OrderedDict to make sure if the OP wan't ordered (hashed) list. – ha9u63a7 Nov 08 '14 at 16:14