[Tutor] Mutable data type in python

Cameron Simpson cs at zip.com.au
Sat Oct 3 07:09:09 CEST 2015


On 02Oct2015 22:22, Anshu Kumar <anshu.kumar726 at gmail.com> wrote:
>When we invoke the same function inside a function (recursive function), i
>want to keep track of some data across all function invocation so i should
>have shareable type but built in data types string, int are not helping as
>they are immutable they are changed while next invocation.
>
>I could use lists which are mutable but sometimes i find it not suitable
>for example when i need only single number or string.

Please provide some more context, perhaps with an example of what you're trying 
to do. What follows is general advice which may not be what you need. Anyway...

What you use depends very much on what you need (trite, but true). Numbers and 
strings are not themselfs mutable.

I'm presuming you want some kind of shared state that continues over the 
recursion, for example a record of what nodes have already been visiting while 
traversing a graph with loops: if you follow a loop you want to stop instead of 
circling/recursing forever.

When I do this I usually form the function somewhat like the below. Let's 
suppose we're walking a graph whose nodes have a ".children" attribute which is 
a list of child nodes. And that the graph might have loops (this node might be 
a child or subchild of itself).

  def traverse(node, seen=None):
    ''' Traverse the graph from `node`, printing each node's name.
        `seen`: if not None, a set of nodes already visited.
    '''
    if seen is None:
      seen = set()
    seen.add(node)
    print(node.name)
    for child in node.children:
      if child not in seen:
        traverse(child, seen)

So the paramater "seen" is your mutable object keeping track of which nodes 
have been visited. You add this node to "seen", then visit any children which 
are not in "seen". You pass "seen" to the traverse() of each child, so all the 
function calls share the same "seen" object.

So in this case we're using a set. There's any number of different things you 
might use depending on what you need to keep track of.

Cheers,
Cameron Simpson <cs at zip.com.au>


More information about the Tutor mailing list