Neil
Neil

Reputation: 8247

How to check if list element is present in array in python

I have a list

bulk_order
Out[230]: 
[3    523
Name: order_id, dtype: object]

And I have an array. Its a series but I am accessing it with values

clusters_order_ids.values
Out[231]: 
array([['520', '521', '524', '527', '532'], ['528'], ['531'],
   ['525', '526', '533'], ['519', '523', '529', '534', '535'], ['530']],     
dtype=object)

Now I want to check whether list element 523 is present in above array and if it is there I want to delete it.

I am doing following in python

bulk_order in clusters_order_ids.values

But It gives me False output

Upvotes: 1

Views: 810

Answers (2)

stoffen
stoffen

Reputation: 569

Your list is not a list, but a list of lists.

If you want to delete the whole list containing something in list ['523']:

orders = [['520', '521', '524', '527', '532'], ['528'], ['531'], ['525', '526', '533'], ['519', '523', '529', '534', '535'], ['530']]
remove_order_with_ids = ['523'] # or bulk_order 
orders = [order for order in orders if not set(remove_order_with_ids).intersection(set(order))]
print orders
# [['520', '521', '524', '527', '532'], ['528'], ['531'], ['525', '526', '533'], ['530']]

If you only want to delete items in ['523'] from the inner list(s):

orders = [['520', '521', '524', '527', '532'], ['528'], ['531'], ['525', '526', '533'], ['519', '523', '529', '534', '535'], ['530']]
remove_order_with_id = ['523'] # or bulk_order 
new_orders = []
for order in orders:
    new_orders.append([item for item in order if item not in remove_order_with_id])
print new_orders
# [['520', '521', '524', '527', '532'], ['528'], ['531'], ['525', '526', '533'], ['519', '529', '534', '535'], ['530']]

Upvotes: 3

tglaria
tglaria

Reputation: 5866

Try this (from Making a flat list out of list of lists in Python):

l = clusters_order_ids.values
out = [item for sublist in l for item in sublist]
print (bulk_order in out)

For the deletion, you'd have to enter on each list so:

for sublist in clusters_order_ids.values:
    if bulk_order in sublist:
        sublist.remove(bulk_order)
        if not sublist:
            #do something to remove the empty list
        break;

Upvotes: 3

Related Questions