[Tutor] Recursive assignment in nested lists
Alan Gauld
alan.gauld at btinternet.com
Sat Aug 4 22:48:06 CEST 2012
On 04/08/12 20:44, Alonzo Quijote wrote:
> There must be a good reason that the responders use a tmp variable like this?
> But I notice that the same effects can be obtained with:
>
> def setValueAtPosition2(list, pos, value):
> for i in pos[:-1]:
> list = list[i]
> list[pos[-1]] = value
>
> Is there something wrong with this latter approach?
Not for the specific case but the problem comes because you lost the
reference to the original list which is usually a bad idea, especially
if you decide you need to do anything with it.
> 2. Another response observes that the function can be defined recursively like this:
> Are the non-recursive solutions better?
Define "better".
Recursive functions in Python have a limit on the recursion depth so for
a very long list it will break. Recursion also tends to use more memory.
Use recursion where you have shallow data structures or very complex
structures which are themselves recursive - then rewrite it without
recursion, but only if necessary due to the above limitations.
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
More information about the Tutor
mailing list