list parameter of a recursive function

Diez B. Roggisch deets at web.de
Thu Oct 7 03:55:01 EDT 2010


TP <Tribulations at Paralleles.invalid> writes:

> Diez B. Roggisch wrote:
>
>> Back to your example: your solution is perfectly fine, although a bit
>> costly and more error-prone if you happen to forget to create a copy.
>> A safer alternative for these cases is using tuples, because they are
>> immutable.
>
> Thanks Diez for your explanation.
> The problem with tuples is that it is not easy to modify them: in my case, I 
> need to append a string to the tuple at each recursive step.
> So, it seems to me that I need to write a loop to modify the tuple, because 
> on a simple example:
>
>>>> a=("foo", "bar")
>>>> b=(a[0],a[1],"toto")
>>>> b
> (u'foo', u'bar', u'toto')
>
> I do not find any other means to obtain that result for b. With lists, I can 
> use ".extend()".
> Am I right?

Yes and no - again. Of course you cannot use extend. But you can
concatenate:

b = a + ("toto",)

Note the trailing comma. A common misconception is to think that tuples
are build using parethesis. They aren't. They are build using the
comma-operator, and needed for disambiguation, e.g. in this case:

foo(a, (b, c))

Diez



More information about the Python-list mailing list