[Tutor] Better structure?

Liam Clarke cyresse at gmail.com
Fri Feb 4 01:33:30 CET 2005


Alan said -
> Its bad practice to delete a member in the collection being iterated
> but Python copes OK if you just change the current item.

Yeah, that's very bad. Makes for all sorts of subtle errors. I usually
do the iteration as a for i in range(len(someList) type thing, and
collect the indexes - like so

j=[1, 2,3,4, 5,6,7,8]
delIndexes=[]

for index in range(len(j)):
     if not j[index] % 2:
        delIndexes.append(index)

delIndexes.reverse()
for item in delIndexes:
     del(j[item])

print j

[1, 3, 5, 7]

Although, (and this will be rough) a list comprehension would be
probably do the same thing
j=[1, 2,3,4, 5,6,7,8]

q = [if not item % 2 for item in j]

I really think I've got that 'if not item % 2' wrong, as I can't test
it, but I'd be hoping for
print q
[1, 3, 5, 7]



-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.


More information about the Tutor mailing list