Errors while using strip and remove on a variable.

Stephen Hansen me+list/python at ixokai.io
Thu Feb 3 12:50:57 EST 2011


On 2/3/11 7:21 AM, anand jeyahar wrote:
> Hi,
>     I am trying to strip a string and then remove on the resulting list
> to remove a set of characters. It works fine with the python shell.
> 
> But after remove the list becomes None, when i am running it from within
> a script.
> 
> I am guessing it has something to do with the way python handles assignment.
> please find the script below*
> 
> a ='oe,eune,eueo, ,u'
> b = a.split(',')
> print b
> c = b.remove('oe')

As others have stated, the issue is that b.remove('oe') doesn't return b
or a copy of b, but directly modifies b instead.

I'll add that you will find that this behavior is consistent throughout
the list api: the None is more then just a default thing that's returned
when nothing else is returned, but in this case its also meant as a
signal to clearly indicate that the list is modified in-place.

Every once in awhile someone asks for these methods that modify the list
itself to either return self, or return a copy of the list -- and I'm
not going to get into that debate -- but the reason for the "None" is to
make it so you WILL get errors like the above.

You only run into this situation with mutable data-types by the way:
strings ALWAYS return a copy or new string, because they can't actually
modify the string itself.


-- 

   Stephen Hansen
   ... Also: Ixokai
   ... Mail: me+list/python (AT) ixokai (DOT) io
   ... Blog: http://meh.ixokai.io/

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 487 bytes
Desc: OpenPGP digital signature
URL: <http://mail.python.org/pipermail/python-list/attachments/20110203/b314685e/attachment-0001.sig>


More information about the Python-list mailing list