0

I have 2 lists:

a=[0,2,0,5]
b=[3,4,5,6]

I want to find remove all the 0 from list a and remove corresponding values(with same index) in list b. My result should be:

a=[2,5]
b=[4,6]

until now I did:

a = [idx for idx, val in enumerate(a) if val == 0] 

and get a=[1,3] but I don't manage to get the corresponding list in b

2 Answers 2

1
a=[0,2,0,5]
b=[3,4,5,6]

a, b = map(list, zip(*[[i, j] for i, j in zip(a, b) if i != 0]))

print(a)
print(b)

Prints:

[2, 5]
[4, 6]
Sign up to request clarification or add additional context in comments.

Comments

0

You got a list indexes correctly, to get valid elements from b list the easy way is to do

[b[idx] for idx, val in enumerate(a) if val != 0] 

and to get a values

[val for val in a if val != 0]

to do it in one iteration:

x = [(val, b[idx]) for idx, val in enumerate(a) if val != 0]

or

x = [(val_a, val_b) for val_a, val_b in zip(a, b) if val_a != 0]

but it gives you list of tuples, but you can use some python magic to turn it into two lists

a, b = map(list, zip(*x))

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.