-1

I have 3 lists, radius, x, and y. Each one is the same length. I want to delete the 'i'th item from each list if the 'i'th item in radius is equal to 0. Below is the code I am trying to use, but for some reason is not working. Thank you in advance!

for i in range(len(radius)):
    if radius[i]==0:
        radius.remove(i)
        x.remove(i)
        y.remove(i)
Alexa
  • 7
  • 1

3 Answers3

1

have you tried?

Breaking this down will give you a good understanding of python variable unpacking, list comprehensions, and how zip works.

x,y, radius = zip(*[(i,j,r) for i,j,r in zip(x,y,radius) if r != 0])
michael_j_ward
  • 4,369
  • 1
  • 24
  • 25
1

You could use list.index to get the index of the 0 element in radius and then just delete it from radius, x and y:

radius = [1, 2, 3, 4, 5, 0, 2]
x = [2, 3, 4, 5, 6, 7, 8]
y = [8, 7, 6, 5, 4, 3, 2]

index = radius.index(0) 

Now that you have the index, delete:

del radius[index], x[index], y[index]

If many zeros exist, you could incorporate this in a loop with a try-catch to break if index cannot find another 0.

Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253
0

This would be a good case for a list comprehension:

In [1]: x, y, r = [1,2,3,4], [1,2,3,4], [1,0,1,0]

In [2]: x, y, r = zip(*[xyr_i for xyr_i in zip(x,y,r) if xyr_i[2] != 0])

In [3]: print(x)
(1, 3)

In [4]: print(y)
(1, 3)

In [5]: print(r)
(1, 1)
evan.oman
  • 5,922
  • 22
  • 43