0

I have a list and I want to delete an optional name but below the line

if newArray[i]==a:

it says "IndexError: list index out of range"

newArray = ['John','Alex','Sophia','Rick']

a = str(raw_input('Type your name if you want to delete : '))
if a in newArray:
    for i in range(len(newArray)):
        if newArray[i]==a:
            del newArray[i] # I want to delete it
        else:
            print newArray[i]   
Dominique
  • 1,080
  • 14
  • 29
Neko
  • 9
  • 6

4 Answers4

0

As the loop progresses, once you've removed an item from newArray it is no longer possible to get to the end of the for loop. If len(newArray) is now 3, you can't get the fourth element, so newArray[3] will raise the error.

A more Pythonic way to do it might be to use a list comprehension.

if a in newArray:
    newArray = [i for i in newArray if i != a]

It could be slower than the .index() method for long lists though (though I'm not about to profile it and see).

nimasmi
  • 3,978
  • 1
  • 25
  • 41
0

Don't iterate and delete element from list at same time.

better do like this:

>>> a = raw_input("enter name to delete: ")
enter name to delete: Alex
>>> a
'Alex'
>>> if a in newArray:
...     del newArray[newArray.index(a)]
... 
>>> newArray
['John', 'Sophia', 'Rick']
Hackaholic
  • 19,069
  • 5
  • 54
  • 72
0

You don't need a for loop for this:

>>> newArray = ['John','Alex','Sophia','Rick']
>>> a = 'Alex'
>>> newArray.index(a)
1
>>> del newArray[newArray.index(a)]
>>> newArray
['John', 'Sophia', 'Rick']
phillchill
  • 116
  • 1
  • 4
  • 1
    What if `a` exists multiple times in that list? – Ahsanul Haque May 05 '17 at 10:11
  • Thank you for helping ^^ – Neko May 05 '17 at 10:18
  • @AhsanulHaque That wasn't the OP's question, but since `.index()` returns the index of the first item the code above would simply remove the first instance of the item from the list. If you want to deal with unique names, have a look at [Sets](https://docs.python.org/3.6/library/stdtypes.html?highlight=set#set-types-set-frozenset) – phillchill May 05 '17 at 13:14
0

You may do it this way as well.

newArray = ['John','Alex','Sophia','Rick']

a = str(raw_input('Type your name if you want to delete : '))

for name in newArray:
   if name == a:
      newArray.remove(name)

print newArray
DineshKumar
  • 1,599
  • 2
  • 16
  • 30