ragzputin
ragzputin

Reputation: 397

Not able to delete string item with colon in python list

So I'm having the following problem while coding in python: I have a few string items in a list like so:

['X','Y','Z','A', 'B:C', 'D']

I want to delete everything past 'Z'. I use the following code to attempt this:

for item in lines:
   if ((item == "A")):
      lines.remove(item)

   if (item == "B:C"):
      lines.remove(item)

   if (item == "D"):
      lines.remove(item)

A and D get removed perfectly. However, B:C is not removed and stays in the list...

Mind you, A, D, B:C etc represent strings, not characters (e.g. A could be Transaction failed! and B:C can represent WRITE failure: cannot be done!)

How can this be solved?

Upvotes: 1

Views: 885

Answers (4)

mgilson
mgilson

Reputation: 310049

Modifying a list while iterating over it is usually a bad thing. Some of the elements get skipped when you remove the current element. You may be able to fix it by iterating over reversed(lines), but it is better to create a new list that doesn't have the elements that you want to drop:

to_remove = {'A', 'B:C', 'D'}
new_lines = [line for line in lines if line not in to_remove]

Or, if you want to modify in-place:

to_remove = {'A', 'B:C', 'D'}
lines[:] = [line for line in lines if line not in to_remove]

Upvotes: 5

farhan chowdhry
farhan chowdhry

Reputation: 57

Firstly you would want to find the position of 'Z' by using the index() method.

x = ['X','Y','Z','A', 'B:C', 'D']
position = x.index('Z')

Then to delete everything after z i would do this:

del x[postion+1:]

You have to add one to the position otherwise it will delete 'Z' also

Upvotes: 0

pacha
pacha

Reputation: 3007

Generally, it is not a good idea to delete elements from a list you are iterating. In your case, you may consider creating a new list with the result you want:

l = ['X','Y','Z','A', 'B:C', 'D']
clean_l = [i for i in l if i not in ('A', 'B:C', 'D')]

Which is a good option if you know which elements you want to delete. However, if you know that you don't want anything after 'Z' regardless of their value, then just slice the list:

clean_l = l[:l.index('Z') + 1]

Upvotes: 0

dot.Py
dot.Py

Reputation: 5157

You may use the .index() method to find the index of a specific element inside a list.

Then after finding the z_index, you may create another list by slicing the first one.

Here's an example:

l1 = ['X','Y','Z','A', 'B:C', 'D']

#finding index of element 'Z'
z_index = l1.index('Z')

#slicing list from 0 until z_index
l2 = l1[:z_index]

print l2

Output:

['X', 'Y']

Upvotes: 1

Related Questions