-5

I want to delete word sabin from the array but it is showing some error...

array=["sabin","ram","hari","sabin"]

length=len(array)


for steps in range(length):
    if(array[steps]=="sabin"):
        print("removed=%s"%(array[steps]))
        del array[steps]


length=len(array)

print(length)
vaultah
  • 44,105
  • 12
  • 114
  • 143
Sabin Bogati
  • 721
  • 8
  • 11

3 Answers3

0

you could do this with a list comprehesion:

array=["sabin","ram","hari","sabin"]

length=len(array)

array = [x for x in array if not x == 'sabin']

length=len(array)
gkusner
  • 1,244
  • 1
  • 11
  • 14
0

The error that you are receiving is an IndexError. This is because you are removing values from the list, while still iterating over it. One possible solution is to use the remove method of the list object to remove instances of "sabin":

array=["sabin","ram","hari","sabin"]

to_remove = 'sabin'

while to_remove in array:
    array.remove(to_remove)
    print("removed=%s"%(to_remove))

print(len(array))

This avoids the IndexError since it is not dependent on the index staying the same throughout the loop.

0

You can use filter too!

my_list = ["sabin","ram","hari","sabin"]
print(my_list)
>>> ['sabin', 'ram', 'hari', 'sabin']
my_list = filter(lambda x: x != 'sabin', my_list)
print(my_list)
>>> ['ram', 'hari']
f.rodrigues
  • 3,499
  • 6
  • 26
  • 62