Simple newbie question

Gerhard Häring gh at ghaering.de
Thu Dec 4 15:33:54 CET 2003


Angelo Secchi wrote:
> Hi, 
> I'm trying to remove lines with zeros from a list "lista".
> The code i'm using is the following:
> 
> for line in lista:
> 	if sum(line == 0) > 0:
> 	lista.remove(line)
> 
> 
> The problem is that the loop stops at the first line with zeros and it
> doesn't remove the other lines with zeros (at least if I do not re-run
> the loop). Probably I do not understand how the loop works.

Two problems here:

1) Don't modify lists while looping over them. Instead, build a new temporary 
list. Something like:

# l is the original list, tmp_l is the temporary list
tmp_l = []
for line in l:
     if {some condition}:
         tmp_l.append(line)

# Now bind l to the modified list:
l = tmp_l

2) "if sum(line ==0) > 0" most probably doesn't do what you want it to do. Hint: 
"line == 0" is a boolean expression that will return either True or False (or 1 
and 0, in older Python versions).

-- Gerhard






More information about the Python-list mailing list