Hasan Saad
Hasan Saad

Reputation: 279

Why is list changing with no reason?

I passed the copy of a list to a function and for some reason the original list changed.I tried everything I could and this is totally illogical or I did something really wrong.

maze="""XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXX            XXXXXXXXXXXXXXXXXXXXX EXX
XXXXXXXXXXXXXX XXX          XXXX     XXX
XX XX           XXX XXXXXXX XXXX XXXXXXX
XX XX XXXXXXXXX XX  XXXXXXX XXXX XXXXXXX
XX XX XXXXXXX XXXXX XXXXXXX XXXX XXXXXXX
XX XX XXXX    XXXXX XXXXX             XX
XX XX XXXX XX XXXXX   XXX XXXXXXXXXXXXXX
XX XX XXXX XX XXXXXXX XXX     XXXX    XX
XX XX      XX     XXX XXXXXXX XXXX XX XX
XX XXXXXXXXXX XXX XXX XXXXXXX      XXXXX
XX      XXXXX XXX XXXXXX      XXXX XXXXX
XXXX XX XXXXX XXX XX     XXXX XXXX   XXX
XXXX XX XXXXX XXX XX XXXXXXXX XXXXXX XXX
XX   XX XXX   XXX XX XXXXX      XXXX XXX
XXXX XX     XXXXX    XXXXX XXXXXXX XXXXX
XXXX XXXXXXXXXXXXXXXXXXXXX XXXXXXX   XXX
XXXX                XXX        XXXXX XXX
XXXXXXXXXXXXXXXX XXXXXX XXXXXX XXXXX XXX
XXX              XXXXXX XXXXXX XXXXX XXX
XXX XXXXXXXXXXXXXXXXX   XX     XXXXX  XX
XXX             XX XX XXXX XXXXXXXXXX XX
XS  XXXXXXXX XXXXX    XXXX            XX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"""
grid=maze.split("\n")
for x in xrange(len(grid)):
    grid[x]=list(grid[x])
row=len(grid)
col=len(grid[0])
def check(maze,x,z,row,col):
    lim=0
    if z+1<col and maze[x][z+1]=="X":
        lim+=1
    if x+1<row and maze[x+1][z]=="X":
        lim+=1
    if z-1>=0 and maze[x][z-1]=="X":
        lim+=1
    if x-1>=0 and maze[x-1][z]=="X":
        lim+=1
    return lim
def get_pos(grida,row,col):
    for l in xrange(100):
        for x in xrange(len(grida)):
            for z in xrange(len(grida[x])):
                if check(grida,x,z,row,col)>=3 and grida[x][z]!="E" and grida[x][z]!="S":
                    grida[x][z]="X"
                else:
                    continue
    return grida
grid_temp=grid[:]
print grid
grid_2=get_pos(grid_temp,row,col)
print grid

I want to know why grid is actually changing.

Upvotes: 1

Views: 396

Answers (3)

You, my friend, are having trouble with namespaces. Try new_array = old_array[:]. This causes a slice in the array, but because there aren't any numbers before or after the colon, it's not cutting anything off, but still forcing a duplicate of the array.

Naming and binding

Names refer to objects. Names are introduced by name binding operations. Each occurrence of a name in the program text refers to the binding of that name established in the innermost function block containing the use.

A block is a piece of Python program text that is executed as a unit. The following are blocks: a module, a function body, and a class definition. Each command typed interactively is a block. A script file (a file given as standard input to the interpreter or specified as a command line argument to the interpreter) is a code block. A script command (a command specified on the interpreter command line with the '-c' option) is a code block. The string argument passed to the built-in functions "eval()" and "exec()" is a code block.

A code block is executed in an execution frame. A frame contains some administrative information (used for debugging) and determines where and how execution continues after the code block's execution has completed.

A scope defines the visibility of a name within a block. If a local variable is defined in a block, its scope includes that block. If the definition occurs in a function block, the scope extends to any blocks contained within the defining one, unless a contained block introduces a different binding for the name. The scope of names defined in a class block is limited to the class block; it does not extend to the code blocks of methods -- this includes comprehensions and generator expressions since they are implemented using a function scope. This means that the following will fail:

class A: a = 42 b = list(a + i for i in range(10))

When a name is used in a code block, it is resolved using the nearest enclosing scope. The set of all such scopes visible to a code block is called the block's environment.

If a name is bound in a block, it is a local variable of that block, unless declared as "nonlocal". If a name is bound at the module level, it is a global variable. (The variables of the module code block are local and global.) If a variable is used in a code block but not defined there, it is a free variable.

When a name is not found at all, a "NameError" exception is raised. If the name refers to a local variable that has not been bound, an "UnboundLocalError" exception is raised. "UnboundLocalError" is a subclass of "NameError".

The following constructs bind names: formal parameters to functions, "import" statements, class and function definitions (these bind the class or function name in the defining block), and targets that are identifiers if occurring in an assignment, "for" loop header, or after "as" in a "with" statement or "except" clause. The "import" statement of the form "from ... import *" binds all names defined in the imported module, except those beginning with an underscore. This form may only be used at the module level.

A target occurring in a "del" statement is also considered bound for this purpose (though the actual semantics are to unbind the name).

Each assignment or import statement occurs within a block defined by a class or function definition or at the module level (the top-level code block).

If a name binding operation occurs anywhere within a code block, all uses of the name within the block are treated as references to the current block. This can lead to errors when a name is used within a block before it is bound. This rule is subtle. Python lacks declarations and allows name binding operations to occur anywhere within a code block. The local variables of a code block can be determined by scanning the entire text of the block for name binding operations.

If the "global" statement occurs within a block, all uses of the name specified in the statement refer to the binding of that name in the top-level namespace. Names are resolved in the top-level namespace by searching the global namespace, i.e. the namespace of the module containing the code block, and the builtins namespace, the namespace of the module "builtins". The global namespace is searched first. If the name is not found there, the builtins namespace is searched. The global statement must precede all uses of the name.

The builtins namespace associated with the execution of a code block is actually found by looking up the name "builtins" in its global namespace; this should be a dictionary or a module (in the latter case the module's dictionary is used). By default, when in the "main" module, "builtins" is the built-in module "builtins"; when in any other module, "builtins" is an alias for the dictionary of the "builtins" module itself. "builtins" can be set to a user-created dictionary to create a weak form of restricted execution.

CPython implementation detail: Users should not touch "builtins"; it is strictly an implementation detail. Users wanting to override values in the builtins namespace should "import" the "builtins" module and modify its attributes appropriately.

The namespace for a module is automatically created the first time a module is imported. The main module for a script is always called "main".

The "global" statement has the same scope as a name binding operation in the same block. If the nearest enclosing scope for a free variable contains a global statement, the free variable is treated as a global.

A class definition is an executable statement that may use and define names. These references follow the normal rules for name resolution. The namespace of the class definition becomes the attribute dictionary of the class. Names defined at the class scope are not visible in methods.

Interaction with dynamic features


There are several cases where Python statements are illegal when used in conjunction with nested scopes that contain free variables.

If a variable is referenced in an enclosing scope, it is illegal to delete the name. An error will be reported at compile time.

If the wild card form of import --- "import *" --- is used in a function and the function contains or is a nested block with free variables, the compiler will raise a "SyntaxError".

The "eval()" and "exec()" functions do not have access to the full environment for resolving names. Names may be resolved in the local and global namespaces of the caller. Free variables are not resolved in the nearest enclosing namespace, but in the global namespace. [1] The "exec()" and "eval()" functions have optional arguments to override the global and local namespace. If only one namespace is specified, it is used for both.

Related help topics: global, nonlocal, ASSIGNMENT, DELETION,DYNAMICFEATURES

Upvotes: 0

Dima Tisnek
Dima Tisnek

Reputation: 11781

Simple solution, use copy module instead of ad hoc copying:

import copy
foo = copy.deepcopy(bar)

To answer your question, I think why comes down to following bit in your code:

grida[x][y] = ...

While your [:] copy only copies one level deep, the assignment is two levels deep.

Upvotes: 1

CoderMD666
CoderMD666

Reputation: 1007

Your grid variable is a 2D array, i.e. a list of lists. When you do grid[:] you are making a new list of lists, but the elements themselves are still references to the same maze row. You want to do a deepcopy, e.g. the deepcopy function from the copy module.

Upvotes: 10

Related Questions