3

I have list in python which has following entries

name-1

name-2

name-3

name-4

name-1

name-2

name-3

name-4

name-1

name-2

name-3

name-4

I would like remove name-1 from list except its first appearance -- resultant list should look like

name-1

name-2

name-3

name-4

name-2

name-3

name-4

name-2

name-3

name-4

How to achieve this ?

2
  • Just name-1, or all duplicates? Is preserving order important? I'm guessing it is, but the problem is much easier if it isn't. Commented Apr 14, 2010 at 13:00
  • the first item should remain as "name-1" - other than that order of remaining items is not important. Commented Apr 14, 2010 at 13:16

5 Answers 5

3
def remove_but_first( lst, it):
    first = lst.index( it )
    # everything up to the first occurance of it, then the rest of the list without all it
    return lst[:first+1] + [ x for x in lst[first:] if x != it ]

s = [1,2,3,4,1,5,6]
print remove_but_first( s, 1)
Sign up to request clarification or add additional context in comments.

2 Comments

lst[:first+1] What does this mean?
a slice from the beginning to the element first+1
2

Assuming name-1 denotes "the first element":

[names[0]] + [n for n in names[1:] if n != names[0]]

EDIT: If the overall goal is to de-duplicate the entire list, just use set(names).

Comments

2

Based on Marcelo's solution:

[name for cnt,name in enumerate(names) if (name != names[0] or cnt > 0)]

Comments

1

Find the index of the first element you wish to remove, then filter the rest of the list. The following works in Python 2.5:

def removeAllButFirst(elem, myList):
    idx = myList.index(elem)
    return myList[0:idx+1] + filter(lambda x: x != elem, myList[idx+1:])

3 Comments

First three lines could be idx = myList.index(elem)
Also myList = myList[0:idx] + ... should probably be myList = myList[0:idx+1] + ... (we need to include the first occurence of 'name1').
Yeah, I just typed in the first thing that came to my head. I couldn't remember the method to find something in a list. I've tested the revised function above, and it does indeed work.
1
mylist = ['name-1', 'name-2', 'name-3', 'name-4', 'name-1', 'name-2', 'name-3', 'name-4', 'name-1', 'name-2', 'name-3', 'name-4']
newlist = filter(lambda x: x != 'name-1', mylist)
newlist.insert(mylist.index('name-1'), 'name-1')
print newlist
['name-1', 'name-2', 'name-3', 'name-4', 'name-2', 'name-3', 'name-4', 'name-2', 'name-3', 'name-4']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.