KawaiKx
KawaiKx

Reputation: 9918

How to remove a list item from another list based on an element's string

I have a list like this:

watchlist = [['NSE:SHIL',1],['NSE:SOLARA',1],['NSE:LINCOLN',1],['NSE:KITEX',1],['NSE:PPL',1],['NSE:PHILIPCARB',1],['NSE:SARLAPOLY',1],['NSE:PANAMAPET',1],['NSE:RPSGVENT',1]]

I want to remove the element list which contains the string 'SOLARA'. New watchlist should be like this:

watchlist = [['NSE:SHIL',1],['NSE:LINCOLN',1],['NSE:KITEX',1],['NSE:PPL',1],['NSE:PHILIPCARB',1],['NSE:SARLAPOLY',1],['NSE:PANAMAPET',1],['NSE:RPSGVENT',1]]

How do I do that?

thanks in advance

Upvotes: 0

Views: 57

Answers (5)

S.B
S.B

Reputation: 16476

This will remove the first sublist which contains the string. If that is your case(There is only one item that has 'SOLARA' inside), there is no need to iterate over every single item in the list using list comprehension, as soon as you find it, delete it and break the loop:

for i, lst in enumerate(watchlist):
    if 'SOLARA' in lst[0]:
        del watchlist[i]
        break

output :

[['NSE:SHIL', 1], ['NSE:LINCOLN', 1], ['NSE:KITEX', 1], ['NSE:PPL', 1], ['NSE:PHILIPCARB', 1], ['NSE:SARLAPOLY', 1], ['NSE:PANAMAPET', 1], ['NSE:RPSGVENT', 1]]

Upvotes: 0

Mortz
Mortz

Reputation: 4879

Use the filter function:

watchlist = list(filter(lambda x: 'SOLARA' not in x[0], watchlist))

Upvotes: 0

Niko B
Niko B

Reputation: 841

The following should do the trick :

watchlist = [['NSE:SHIL',1],['NSE:SOLARA',1],['NSE:LINCOLN',1],['NSE:KITEX',1],['NSE:PPL',1],['NSE:PHILIPCARB',1],['NSE:SARLAPOLY',1],['NSE:PANAMAPET',1],['NSE:RPSGVENT',1]]
filter_string = "SOLARA"
filtered_watchlist = [i for i in watchlist if filter_string not in i[0]]

Upvotes: 0

Thekingis007
Thekingis007

Reputation: 647

You can use list comprehension:

watchlist = [['NSE:SHIL',1],['NSE:SOLARA',1],['NSE:LINCOLN',1],['NSE:KITEX',1],['NSE:PPL',1],['NSE:PHILIPCARB',1],['NSE:SARLAPOLY',1],['NSE:PANAMAPET',1],['NSE:RPSGVENT',1]]
new_watchlist = [ele for ele in watchlist if 'SOLARA' not in ele[0]]

print(new_watchlist)

Output:

[['NSE:SHIL', 1], ['NSE:LINCOLN', 1], ['NSE:KITEX', 1], ['NSE:PPL', 1], ['NSE:PHILIPCARB', 1], ['NSE:SARLAPOLY', 1], ['NSE:PANAMAPET', 1], ['NSE:RPSGVENT', 1]]

Upvotes: 0

user2668284
user2668284

Reputation:

Here's one way you could do it:

watchlist = [['NSE:SHIL',1],['NSE:SOLARA',1],['NSE:LINCOLN',1],['NSE:KITEX',1],['NSE:PPL',1],['NSE:PHILIPCARB',1],['NSE:SARLAPOLY',1],['NSE:PANAMAPET',1],['NSE:RPSGVENT',1]]

watchlist = [e for e in watchlist if not 'SOLARA' in e[0]]

print(watchlist)

Upvotes: 1

Related Questions