Need help removing list elements.
John Machin
sjmachin at lexicon.net
Sat Apr 29 17:47:02 EDT 2006
On 30/04/2006 12:22 AM, Max Erickson wrote:
> nuffnough at gmail.com wrote in
> news:1146316090.540227.278230 at j73g2000cwa.googlegroups.com:
>
>> But this gives me "IndexError: list out of range
>
> You are making the list shorter as you are iterating. By the time your
> index is at the end of the original list, it isn't that long any more.
If you are hell-bent on conditionally deleting items from a list in
situ, you need to do it backwards:
for i in xrange(len(alist)-1, -1, -1):
if not_interested(alist[i]):
del alist[i]
> Creating a new list and appending the elements you want to keep avoids
> the problem. Or you can just use a list comprehension(untested):
>
> returned_lines=[line for line in open("lines.txt", 'rb')
Call me crazy, but I wouldn't open the file in BINARY mode :-)
> if line != ""]
>
> or just
>
> returned_lines=[line for line in open("lines.txt") if line]
For a modicum of extra effort, the condition "if line.strip()" throws
away lines containing only whitespace.
However I don't see the point of creating a list of lines, then throwing
out only *some* of the uninteresting ones. IMHO the OP might be better
advised to read the file one line at a time, ignoring
blank/empty/comment lines, then *validate* the remainder. Hint: with the
semi-squished-list approach, you can't report the original line number
of any erroneous line without extra effort.
The OP might be even better advised to (read the source of, use) an
existing config file parser module.
Hope some of this helps,
John
More information about the Python-list
mailing list