Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

parsing list in python

Tags:

python

list

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 ?

like image 994
webminal.org Avatar asked Apr 13 '26 00:04

webminal.org


2 Answers

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)
like image 105
Jochen Ritzel Avatar answered Apr 16 '26 21:04

Jochen Ritzel


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).

like image 29
Marcelo Cantos Avatar answered Apr 16 '26 23:04

Marcelo Cantos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!