Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)

I'm trying to delete some of the elements from array this way:

a = [2, 5, 10, 20, 30, 40]

for i in range(len(a)):

  print(a[i], i)

  if (a[i] > 20):

    a = np.delete(a, i)

print(a)

And I am getting an error:

 index 5 is out of bounds for axis 0 with the size 5.

 I don't really understand what's wrong with my code above. 

1 Answer

0 votes
by (36.8k points)
edited by

so, you deleted the [30] element from the list, your list the last index will be 4, then you will access a[5] -> error!

a = [2, 5, 10, 20, 30, 40]

a2 = []

for i in a:

  print(i)

  if (i <= 20):

    a2.append(i)

print(a2)

output

2

5

10

20

30

40

[2, 5, 10, 20]

Want to gain skills in Data Science with Python? Sign up today for this Data Science with Python Course and be a master in it

Browse Categories

...