Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete from list?

Tags:

python

Assuming I have the following list:

array1 = ['A', 'C', 'Desk']

and another array that contains:

array2 = [{'id': 'A', 'name': 'Greg'}, 
{'id': 'Desk', 'name': 'Will'},
{'id': 'E', 'name': 'Craig'},
{'id': 'G', 'name': 'Johnson'}]

What is a good way to remove items from the list? The following does not appear to work

for item in array2:
   if item['id'] in array1:
     array2.remove(item)
like image 576
Setsuna Avatar asked Nov 24 '25 08:11

Setsuna


1 Answers

You could also use a list comprehension for this:

>>> array2 = [{'id': 'A', 'name': 'Greg'},
... {'id': 'Desk', 'name': 'Will'},
... {'id': 'E', 'name': 'Craig'},
... {'id': 'G', 'name': 'Johnson'}]
>>> array1 = ['A', 'C', 'Desk']
>>> filtered = [item for item in array2 if item['id'] not in array1]
>>> filtered
[{'id': 'E', 'name': 'Craig'}, {'id': 'G', 'name': 'Johnson'}]
like image 193
sberry Avatar answered Nov 25 '25 21:11

sberry



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!