简体   繁体   中英

“for item in list” - where does the None item come from?

i got this list of objects with one item in it.

    print self.parameters
    print len(self.parameters)
    for p in self.parameters:
        print p

when i print out the list and len of the lsit i see the expected: one item. But when looping over the lsit i also get a None item...!?

[<__main__.Parameter object at 0x00000000022D4828>]
1
<__main__.Parameter object at 0x00000000022D4828>
None

what is going on here? (yes im sure, that the "None" output is from this print statement)


EDIT: i was manipulating the list i was looping over:

print self.parameters
print len(self.parameters)
for p in self.parameters:
    print p
    (...)
    self.parameters.append(<something that returned None>)

Don't do this.

for p in self.parameters:
    print p
    ...
    self.parameters.append(...) # No.

See Modifying list while iterating -- basically, you shouldn't modify something while iterating over it. You can make a copy if you want:

for p in list(self.parameters):
    print p
    ...
    self.parameters.append(...) # Okay

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM