On Mar 27, 4:39 am, TP <tribulati...@paralleles.invalid> wrote:
> Hi everybody,
>
> Be a the following list, containing list elements which second field is a
> string.
>
> >>> a = [ [4, "toto"], [5, "cou"] ]
> >>> a[0][1]="tou"
> >>> a
>
> [[4, 'tou'], [5, 'cou']]
>
> OK.
>
> Now, I want:
> * to do the same modification on the list "a" within a function
> * not to hardcode in this function the position of the string in each
> element of a.
>
> At first sight, we think at defining a function like this:
>
> def assign( text_accessor, list_elem, new_textvalue ):
>
>     text_accessor( list_elem ) = new_textvalue
>
> and then doing:
>
> assign( lambda elem: elem[1], a[0], "co" )
>
> But it does not work, we obtain:
>
>     text_accessor( list_elem ) = new_textvalue
> SyntaxError: can't assign to function call
>
> In fact, we should work on the address of text_accessor( list_elem ). How to
> do that?

There is always the __setitem__ method, either bound to the object in
question, or along with an instance and its class.

>>> def f( fun, ind, val ):
...     fun( ind, val )
...
>>> a= [ None ]
>>> f( a.__setitem__, 0, 'abc' )
>>> a
['abc']

Or, you could require your instances to all have a method name to
accomplish it, or use operator.__setitem__.
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to