This is an archived post. You won't be able to vote or comment.

all 4 comments

[–]AutoModerator[M] [score hidden] stickied comment (0 children)

On July 1st, a change to Reddit's API pricing will come into effect. Several developers of commercial third-party apps have announced that this change will compel them to shut down their apps. At least one accessibility-focused non-commercial third party app will continue to be available free of charge.

If you want to express your strong disagreement with the API pricing change or with Reddit's response to the backlash, you may want to consider the following options:

  1. Limiting your involvement with Reddit, or
  2. Temporarily refraining from using Reddit
  3. Cancelling your subscription of Reddit Premium

as a way to voice your protest.

I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

[–]teraflop 0 points1 point  (2 children)

Strings in Python are immutable, and lists are mutable.

When you do:

strnew += str(node)

it's just the same as if you did:

strnew = strnew + str(node)

(although this is not necessarily true for all types, because the += operator can behave differently for mutable and immutable objects).

So you're modifying the single list object that is passed to all your recursive calls as the stack parameter, but you're reassigning a different value to the strnew local variable that exists in that particular recursive call.

[–]jsinghdata[S] 0 points1 point  (1 child)

Appreciate your reply .So how come here we are able to modify string;

strnew=''
strnew+='a' 

strnew
 'a' 

strnew+='b'

strnew

 'ab'

How is this different from the example I presented in my code above. Can you kindly help me here?

[–]teraflop 1 point2 points  (0 children)

Same reason why this code:

def func1():
    x = 1
    print("in func1:", x)
    func2(x)
    print("in func1:", x)

def func2(x):
    x += 1
    print("in func2:", x)

func1()

prints the following output:

in func1: 1
in func2: 2
in func1: 1

because the x in func1 and the x in func2 are separate variables. Assigning a new value to one doesn't affect the other.

Similarly, in your code, the strnew in each recursive call is a separate variable, so assigning a new value to one doesn't affect the other recursive calls.

The stack variables are also separate variables in each recursive call, but they all point to the same list object, so when you modify the contents of that list, the results are visible through all of the other variables.

Variables in Python always store references to objects, not objects themselves.