1

I writing a program that takes an initial sequence and performs 3 functions on it and then spits out the 3 answers but I want to keep the original variable intact so it can be reused. From other answers on the forum I have concluded that the variable within a function should be local but it appears to be acting globally.

from collections import deque
from sys import exit
initial_state = (1,2,3,4,5,6,7,8)
initial_state = deque(initial_state)

def row_exchange(t):
    t.reverse()
    return t
def rt_circ_shift(t):
    t.appendleft(t[3])
    del t[4]
    t.append(t[4])
    del t[4]
    return t
def md_clk_rot (t):
    t.insert(1,t[6])
    del t[7]
    t.insert(3,t[4])
    del t[5]
    t.insert(4,t[5])
    del t[6]
    return t



print(row_exchange(initial_state))
print(initial_state)
print(rt_circ_shift(initial_state))
print(md_clk_rot(initial_state))

I would expect to get:

deque([8, 7, 6, 5, 4, 3, 2, 1])
deque([1, 2, 3, 4, 5, 6, 7, 8])
deque([4, 1, 2, 3, 6, 7, 8, 5])
deque([1, 7, 2, 4, 5, 3, 6, 8])

but instead I get:

deque([8, 7, 6, 5, 4, 3, 2, 1])
deque([8, 7, 6, 5, 4, 3, 2, 1])
deque([5, 8, 7, 6, 3, 2, 1, 4])
deque([5, 1, 8, 6, 3, 7, 2, 4])

so why isn't my variable local within the function? is there a way I can rename the output within the function so that it isn't using the same identifier initial_state? I'm pretty new to programming so over explanation would be appreciated.

Community
  • 1
  • 1

1 Answers1

1

Per the docs for deque.reverse:

Reverse the elements of the deque in-place and then return None.

(my emphasis). Therefore

def row_exchange(t):
    t.reverse()
    return t

row_exchange(initial_state)

modifies initial_state. Note that append, appendleft and insert also modify the deque in-place.


To reverse without modifying t inplace, you could use

def row_exchange(t):
    return deque(reversed(t))

In each of the functions, t is a local variable. The effect you are seeing is not because t is somehow global -- it is not. Indeed, you would get a NameError if you tried to reference t in the global scope.


For more on why modifying a local variable can affect a value outside the local scope, see Ned Batchelder's Facts and myths about Python names and values. In particular, look at the discussion of the function augment_twice.

unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677