3

I've a list

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

b = [10,11,12,13,14,15,16,17,18]

While traversing list b , if any number is less than 15, then remove its corresponding number (index) from list a.

For eg:- in list b 10,11,12,13,14 are less than 15, hence its counterpart from list a should be removed, ie 1,2,3,4,5.

Currently, this is how I'm doing:

for index, i in enumerate(b):
    if i < 15:
        del(a[index])

This returns me an out of range index error.

How can I do this?

Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176
Praful Bagai
  • 16,684
  • 50
  • 136
  • 267

3 Answers3

9

You should use list comprehension and zip and instead of deleting elements from a , instead take elements in a whose b value is over 15. Example -

a[:] = [i for i,j in zip(a,b) if j >=15]

We are using a[:] on the left side, so that a list object gets mutated inplace. (This is different from a = <something> as the latter simply binds name a to a new list whereas former mutates the list inplace).


Demo -

>>> a = [1,2,3,4,5,6,7,8,9]
>>>
>>> b = [10,11,12,13,14,15,16,17,18]
>>> a[:] = [i for i,j in zip(a,b) if j >=15]
>>> a
[6, 7, 8, 9]
Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176
2

When I ran it, I didn't get an index error, but I ended up producing a = [2, 4, 6, 8]. One problem could be that as soon as you start deleting elements of a, moving left to right, its index will shift, and will no longer align with that of b. I tried counting backwards instead (and I skipped on using enumerate, as I'm a noob and I find it hard to remember how it works):

for i in range(len(b)-1,-1,-1):
    if b[i] < 15:
        del(a[i])
C. Murtaugh
  • 574
  • 4
  • 15
  • Hahah way to game the system! While i applaud you for getting around the index error. This is still feels wrong. :thumbs_up: nonetheless! – Javier Buzzi Oct 16 '15 at 05:02
  • 1
    @JavierBuzzi, Perhaps it feels wrong because its worst case complexity is quadratic – John La Rooy Oct 16 '15 at 05:13
  • I didn't want to be mean and pick apart OPs response. Reminds me of myself when i was 15 - i would keep trying things until it worked. hahah good times – Javier Buzzi Oct 16 '15 at 14:01
0

Try using Temp list

  >>> a = [1,2,3,4,5,6,7,8,9]
  >>> b = [10,11,12,13,14,15,16,17,18]
  >>> c=[]
  >>> for i in range(0,len(b),1):
           if b[i]>=15:
                 c.append(a[i])

  >>> a=c
  >>> a
  [6, 7, 8, 9]
Ravichandra
  • 2,162
  • 4
  • 24
  • 36