list comprehension problem

mk mrkafk at gmail.com
Thu Oct 29 11:12:18 EDT 2009


Hello everyone,

print hosts
hosts = [ s.strip() for s in hosts if s is not '' and s is not None and 
s is not '\n' ]
print hosts

['9.156.44.227\n', '9.156.46.34 \n', '\n']
['9.156.44.227', '9.156.46.34', '']

Why does the hosts list after list comprehension still contain '' in 
last position?

I checked that:

print hosts
hosts = [ s.strip() for s in hosts if s != '' and s != None and s != '\n' ]
print hosts

..works as expected:

['9.156.44.227\n', '9.156.46.34 \n', '\n']
['9.156.44.227', '9.156.46.34']


Are there two '\n' strings in the interpreter's memory or smth so the 
identity check "s is not '\n'" does not work as expected?

This is weird. I expected that at all times there is only one '\n' 
string in Python's cache or whatever that all labels meant by the 
programmer as '\n' string actually point to. Is that wrong assumption?



Regards,
mk




More information about the Python-list mailing list