0

A small section of my program. A and B are suppose to be different but come out the same. A = B even after changing. Any suggestions.

def reveal_board(location1, location2, a):
    b = a
    for char in board:
        if char == board[location1 - 1]:
            b[location1 - 1] = char
        if char == board[location2 - 1]:
            b[location2 - 1] = char
        else:
            b = b
    print_board(b)
    if board[location1 - 1] == board[location2 - 1]:
        return b
    else:
        return a
EdChum
  • 376,765
  • 198
  • 813
  • 562
Stephanie
  • 47
  • 5

2 Answers2

5

Assuming that a and b are a more complex object such as a list or a dictionary, you're not actually making a copy of a when assigning b = a. This merely makes a and b both point to the same object. If you then modify b, you are also modifying a and vice versa.

If you want to make a copy, consider something like b = list(a) or b = dict(a). Or, more generally:

import copy
b = copy.copy(a)

or even

import copy
b = copy.deepcopy(a)

to make a deep copy.

Joost
  • 4,094
  • 3
  • 27
  • 58
  • It doesn't look like you need a deep copy, so it's better to just use `b = a[:]` – Tom Karzes Nov 02 '15 at 09:42
  • @TomKarzes why do you think `b = a[:]` is preferable over `b = list(a)` or `b = copy.copy(a)`? Don't optimise at this level. – Joost Nov 02 '15 at 10:19
  • @Joost if it's built into the language, and avoids loading a package you don't need, then it's pretty much always preferable. You should only load a package if you need it for something that isn't immediately available in the language. Using the list constructor is ok, but using copy is excessive. – Tom Karzes Nov 02 '15 at 11:38
1

The assignment b = a isn't copying a, but is merely copying a reference to the same list that a references. To actually copy it, replace the assignment with:

b = a[:]

That will create a "shallow" copy of a and is simpler and faster than using copy.

Also, I suggest getting rid of the self-assignment of b to itself. That doesn't make sense. You can just delete that and the else above it:

else:
    b = b
Tom Karzes
  • 22,815
  • 2
  • 22
  • 41