0

Let's say I have two equal-length lists, list1 and list2, both consisting of a bunch of numbers. I want to remove all the elements of list1 that don't meet a certain criterion. Simple enough. How would I also remove the corresponding elements from list2 though? If I remove, say, the 5th element of list1, I would also like to remove the 5th element of list2. Example of what I'm trying to do below:

list1 = [i for i in list1 if i >= 1]
list2 = list2 #but with the corresponding values of list1 removed from list2 as well

I could come up with, say,

list2_temp = []
for j in range(len(list1)):
    if list1[j] >= 1:
        list2_temp.extend(list2[j])

list1 = [i for i in list1 if i >= 1]

but I am looking for a more "Pythonic" way to do it, specifically if there is any way I can use list comprehensions on list2 as well as list1. Any ideas/suggestions?

2 Answers 2

4

Combine, filter, split:

list1[:], list2[:] = zip(*((x, y) for (x, y) in zip(list1, list2) if predicate(x)))
2
  • if for each xs in predicate are False ..... ValueError: need more than 0 values to unpack ...... how can i fix this ? Sep 11, 2015 at 21:27
  • Defer the assignment until you can check if there's any results, and then use del list1[:], list2[:] if there aren't any. Sep 11, 2015 at 21:29
1

I think that maybe the problem is that you have 2 parallel lists rather than a single list that holds items which have the all the data for each element.

Think of the data as a spreadsheet -- Currently you have 2 columns and you want to filter the rows by the values in one column. Rather than modeling the data as a bunch of columns, it's better to model it as a list of rows.

To fix the problem now you can zip the lists together, filter them and then unzip at the end:

items = [(i, j) for i, j in zip(list1, list2) if i >= 1]
tuple1, tuple2 = zip(*items)

but I still recommend considering storing the data in a different way...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.