apples-oranges - 1 year ago 91
Python Question

# Remove item in a list based on index

I'm trying to solve a little puzzle, where I need to delete the number 13, and the number after that in a list (its an exercise on CodingBat).

This is my code:

``````n = [1, 2, 3, 13, 5, 13]

for i in n:
if i == 13:
n.remove(i) and n.remove(n.index(i+1))

print n
``````

Desired output:
`[1, 2, 3]`

However, my incorrect output is:
`[1, 2, 3, 5] #the item after 13 (i.e. 5) did not get deleted`

I thought that this
`n.remove(n.index(i+1))`
would remove the item after 13, but it doesn't.

This should work:

``````n = [1, 2, 3, 13, 5, 13]

for i in n:
if i == 13:
n.remove(n[n.index(i)+1]) # remove the element after `i` first
n.remove(i)

print n
``````

A while loop for the problem:

``````n = [1, 2, 3, 13, 5, 13]

i = 0
while i < len(n):
if n[i] == 13:
n.pop(i)
if i < len(n):
n.pop(i)
else:
i = i + 1

print n

# [1, 2, 3]
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download