0

I have a list:

bigdumblist = [
    (0, 0, {'product_id': 2, 'product_uom_qty': 90}),
    (0, 0, {'product_id': 3, 'product_uom_qty': 5}),
    (0, 0, {'product_id': 5, 'product_uom_qty': 69})
]

I want to remove all items from the list where 'product_id' is not 2 or 3, like so:

[
   (0, 0, {'product_id': 2, 'product_uom_qty': 90}),
   (0, 0, {'product_id': 3, 'product_uom_qty': 5})
]

What I have tried:

def not_in(item):
    if item["product_id"] is not 2 or 3:
        bigdumblist.remove((0, 0, {'product_id': 5, 'product_uom_qty': 69}))

for _, _, item in bigdumblist:
    not_in(item)
    break

print(bigdumblist)

Which works but obviously including (0, 0, {'product_id': 5, 'product_uom_qty': 69}) is not a solution. How can I properly remove specific items in the list?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
apexprogramming
  • 403
  • 2
  • 14

6 Answers6

3

You could use a list comprehension like so:

[x for x in bigdumblist if x[2]['product_id'] in [2,3]]
Franz
  • 357
  • 3
  • 11
1

You shouldn't modify a list while you're iterating over it. You could make a copy of the list first, but it's simpler to use a list comprehension.

Since the list comprehension specifies which elements to keep rather than delete, the condition must be inverted.

bigdumblist = [item for item in bigdumblist if item[2]['product_id'] in (2, 3)]

Note that

if item["product_id"] is not 2 or 3:

is parsed as if it were

if (item["product_id"] is not 2) or 3:

Since 3 is always truthy, this condition will always succeed. Logical operators like and and or are not automatically distributed over relational operators.

Barmar
  • 741,623
  • 53
  • 500
  • 612
0

Try a conditional list comprehension like this....

[x for x in bigdumblist if x[2]['product_id'] in [2,3]]

caldweln
  • 126
  • 3
0

You should really use list comprehension for that kind of filter, something like this:

bigdumblist = [
    (0, 0, {'product_id': 2, 'product_uom_qty': 90}),
    (0, 0, {'product_id': 3, 'product_uom_qty': 5}),
    (0, 0, {'product_id': 5, 'product_uom_qty': 69})
]

newlist = [i for i in bigdumblist if i[2]['product_id'] not in [2,3]]
Gustavo Kawamoto
  • 2,665
  • 18
  • 27
0

List comprehension is one way to do this.

You probably want something similar to:

filtered_list = [item for item in original_list if item["product_id"] in (2, 3)]

Another option is filter:

def valid_products(item):
    return item["product_id"] in (2,3)

filtered_list = list(filter(valid_products, original_list))
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
edgars
  • 1,038
  • 1
  • 7
  • 17
-1
items = [item for item in bigdumblist if item item[2]['product_id'] in (2,3)]
AnGG
  • 679
  • 3
  • 9