2

I am a beginner to Python so bear with me. Basically I am searching a particular table cell for the forward slash character. If the cell contains that character, I want to delete the entire row.

counter = 0
for row in table:
    if row[7].find("/") != -1:
        del table[counter]
        continue
    counter+=1

The code above never detects the forward slash but finds any other character I substitute for forward slash. Any help would be much appreciated.

2
  • Why the index 7? Use the syntax "/" in row[7], it's much more Pythonic. You should really avoid deleting elements of the list you're iterating over as that causes undefined behaviour. You can also use for counter, row in enumerate(table): and avoid having to keep your own counter variable. Commented Dec 10, 2010 at 17:10
  • @marcog: Unfortunately enumerate() can't help in this case. Commented Dec 10, 2010 at 17:23

2 Answers 2

4

There's so many things wrong with that code it's easier to just re-write it.

table[:] = [row for row in table if '/' not in row[7]]
Sign up to request clarification or add additional context in comments.

4 Comments

If you take the time to answer you might as well take the time to explain what was wrong in the original code
Thanks, this worked perfectly. Like I said, I am a beginner and am just picking up on all the syntax.
@Tyler: The biggest thing to remember is to never modify a sequence you're iterating over.
Another quick question regarding this and I promise to leave you alone. Using the same format as above, how would I delete the row if the element in row[7] wasn't between the numbers 1 to 10.
-2

Could you not just maybe do..

for row in table:
    if '/' in row[7]:
        row.delete()

Or if you really need the counter to del the row from the table, then just put the counter back in.

7 Comments

This code will do nothing. The name row is defined by the loop and not a reference to anything in table.
This code should work fine, I cannot see what your are saying.
del deletes names, not objects. That objects may be deleted by executing it is incidental.
-1 It's wrong as Ignacio states. Try it out: xs = range(N); for x in xs: del x leaves xs untouched.
I wasnt fully trying to write code i just snapped it out without thinking what del means in python.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.