0
list1 = [0,10,20,0,40,50] 
list2 = [1,2,3,4,5,6] 
list3 = []

I want to remove all the zeros from list1 and the respective elements from list2. I am able to remove the zeros from list1, but I can't remove the respective elements from list2.

for i in list1[:]:
    if i != 0:
    list3.append(i)
                               
for i in range(len(list3)):
    list2.append(i)
                
for i in list3[:]:
    list2.remove(i)


Desired result:
    list1 = [10,20,40,50]
    list2 = [2,3,5,6]
Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70
Afroboy23
  • 31
  • 9

5 Answers5

3

Here is a way of doing that, you did not give any info about that list3. Try this code below:

list1 = [0, 10, 20, 0, 40, 50]
list2 = [1, 2, 3, 4, 5, 6]

# Indexes of the elements to remove
indexes_to_remove = [i for i, x in enumerate(list1) if x == 0]

# Remove the elements from list1 and list2 in reverse order to avoid issues
for i in reversed(indexes_to_remove):
    del list1[i]
    del list2[i]

# Return lists
print(list1)
print(list2)
3

Always happy to compress (Try it online!):

from itertools import compress

list2[:] = compress(list2, list1)
list1[:] = filter(None, list1)

Or (Try it online!):

list1[:], list2[:] = zip(*compress(zip(list1, list2), list1))
Kelly Bundy
  • 23,480
  • 7
  • 29
  • 65
1

You can try the below:

list1 = [0, 10, 20, 0, 40, 50] 
list2 = [1, 2, 3, 4, 5, 6] 
list3 = []

for i, num in enumerate(list1):
    if num != 0:
        list3.append(num)
    else:
        del list2[i]

print(list3)  # [10, 20, 40, 50]
print(list2)  # [2, 3, 5, 6]
Abdulmajeed
  • 1,502
  • 2
  • 10
  • 13
1

Make sequential zip of two input lists with the needed filtering:

list1, list2 = map(list, zip(*[t for t in zip(list1, list2) if t[0] != 0]))
print(list1)
print(list2)

[10, 20, 40, 50]
[2, 3, 5, 6]
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
1

I'm too reputation-poor to make a comment on Kelly's answer, but the use of itertools.compress made me want to do this.

from itertools import compress

list1 = [0,10,20,0,40,50] 
list2 = [1,2,3,4,5,6]

list2 = list(compress(list2, list1))
list1 = [x for x in list1 if x != 0]

It's not a one liner like Kelly's but perhaps a little easier to grok.

natty
  • 69
  • 6