Better solution

Hans Nowak wurmy at earthlink.net
Tue Aug 20 23:23:31 CEST 2002


holger krekel wrote:
> Michael Hudson wrote:
> 
>>holger krekel <pyth at devel.trillke.net> writes:
>>
>>
>>>>If you want to mutate the list, I'd say:
>>>>
>>>>lst[:] = filter(None, lst)
>>>>
>>>>is better than the monstrosity above.
>>>
>>>why the '[:]'? 
>>>
>>>doesn't seem to make any difference here unless
>>>filter is allowed to return the same lst-object.
>>
>>It depends whether you want to change the acutal list object or merely
>>have 'lst' refer to a changed list.  Bo was using .pop in his
>>question, so it's possible he wanted the former.
> 
> 
> Aehem. i must be missing something obvious. 
> 
> Yes, append/sort/pop and friends are inplace-methods.
> 
> But isn't 
> 
>     filter(None,lst) 
> 
> supposed to return a new list? 

Yes, it does return a new list, but the lst[:] syntax replaces the contents of 
the existing list object with those of the new one (as returned by filter). 
This is different from lst = filter(...) where you rebind the name 'lst' to the 
new list object returned by filter.

 >>> a = [1, 2, 3]
 >>> id(a)
9492200
 >>> b = [4, 5, 6]
 >>> id(b)
9546888  # different list, different id
 >>> a[:] = b
 >>> a
[4, 5, 6] # new contents, but...
 >>> id(a)
9492200   # still the same id! ^_^
 >>> a = b
 >>> a
[4, 5, 6]
 >>> id(a)
9546888  # now it has the same id as b

HTH,

-- 
Hans (base64.decodestring('d3VybXlAZWFydGhsaW5rLm5ldA=='))
# decode for email address ;-)
The Pythonic Quarter:: http://www.awaretek.com/nowak/
Kaa:: http://www.angelfire.com/jazz/aquila/blog/blogger.html




More information about the Python-list mailing list