Skip to content
Advertisement

How to optimize code for deleting n position in all the lists from a list of lists

I search the site for this issue and I found many posts about deleting specific values from list of lists.

However, this doesn’t answer my question.

Lets have:

mylist=[[1,2,3,4],[100,374,283,738]]

Now, in my mind the two lists are linked. List 1 number items: 1, 2, 3, 4,… and list 2 a feature of these items (for example prices: $100, $374, etc).

Now, I want to delete from the list the elements (number and price) if list2 is hihger of a certain value (for example if an item is too expensive, more than $300)

I have been trying and I got this:

n=0 # counter for position in the list
for i in mylist[1]:
    if i>300:
        for j in mylist:
            del j[n]
    n=n+1

result:

[[1,3],[100,283]]

This actually works. It looks not too efficient: I have to access the list several times and I have to create new variables. Too many loops.

Since lists can use comprehension lists I was wonder if there is a more efficient and elegant method getting same result

Thanks

Advertisement

Answer

Use zip with a filtering generator expression:

>>> mylist = [[1,2,3,4], [100,374,283,738]]
>>> mylist[:] = list(map(list, zip(*((a,b) for a,b in zip(*mylist) if b<300))))
>>> mylist
[[1, 3], [100, 283]]

Note that this keeps the old mylist pointer, to mimic the way your code modifies the original list.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement