[Tutor] Iterating through a list of strings

Luke Paireepinart rabidpoobear at gmail.com
Mon May 3 10:19:22 CEST 2010


> If that looks a bit clumsy, use a generator expression:
>
> linesToDelete = [x for x in lines if x.startswith('%')]
> for x in linesToDelete:
>   lines.remove(x)
>
> which idiomatically should probably become:
>
> for x in [y for y in lines if y.startswith('%')]:
>   lines.remove(x)
>
>

Hmm, why not
lines = [line for line in lines if not line.strip().startswith('%')]

note that for a significantly large file this might be sorta slow
(since it's an extra iteration over the list), whereas the 'breaking
out of the loop on comment lines' approach may be a little faster.
it's probably not significant for this application though.

Also, yeah, try really hard not to modify lists you're iterating over.
 In almost every case, it's not actually what you need to do.  It's
akin to people wanting to create variable names from strings, before
they discover that dictionaries are the correct response.

Hope that helps,
-Luke


More information about the Tutor mailing list