0

Let's say I have two lists:

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

Based on a, I want to remove the value at that index for both lists if it's even. I thought of using a zip:

c = [i for i in zip(a,b) if i[0] % 2 == 0]

But now how can I turn [(2, 6), (4, 8)] back into two separate lists? As:

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

Obviously I can use two list comprehensions, but I was curious if it's possible to do that in one line with some built-in python function. Something like:

a, b = somefunc(c)
Shane Smiskol
  • 952
  • 1
  • 11
  • 38

1 Answers1

1

You can use zip again

a = [1, 2, 3, 4]
b = [5, 6, 7, 8]
a, b = zip(*[i for i in zip(a,b) if i[0] % 2 == 0])

See this answer for more details on why zip(*...) undoes zip(...).

Josiah Yoder
  • 3,321
  • 4
  • 40
  • 58
meTchaikovsky
  • 7,478
  • 2
  • 15
  • 34