modifying a list element from a function
Peter Otten
__peter__ at web.de
Fri Mar 27 06:53:39 EDT 2009
TP 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?
You can understand Python to some extend if you liken its variables to
pointers, but here the analogy breaks: you cannot have pointers to
pointers. To parameterize list item access you can either pass the index or
a setter (and if needed a getter) function:
>>> a = [ [4, "toto"], [5, "cou"] ]
>>> def assign(setitem_n, items, value):
... setitem_n(items, value)
...
>>> def setitem1(items, value):
... items[1] = value
...
>>> assign(setitem1, a[0], "XX")
>>> a
[[4, 'XX'], [5, 'cou']]
Peter
More information about the Python-list
mailing list