0

I am using jupyter ide and I am getting different results for print(word) and appending to lst.

word = ["M","A","R","I","N","E"]
goal = ["A","I","R","M","E","N"]
lst = []

def search(ind_a,a,b,word):
    for x in range(len(word)):
        if word[x] == b:
            temp=b
            word[x]=word[ind_a]
            word[ind_a]=temp
            return word

def sequence(word,goal):
    for ind_x,x,y in zip(range(len(word)),word,goal):
        if(x==y):
            continue
        word=search(ind_x,x,y,word)
        print(word)
        lst.append(word)
    return lst

when I called sequence(word,goal),I get succeding out:

sequence(word,goal)

Output:

['A', 'M', 'R', 'I', 'N', 'E']#print word statement
['A', 'I', 'R', 'M', 'N', 'E']
['A', 'I', 'R', 'M', 'E', 'N']
Out[193]:
[['A', 'I', 'R', 'M', 'E', 'N'],#return statement
 ['A', 'I', 'R', 'M', 'E', 'N'],
 ['A', 'I', 'R', 'M', 'E', 'N']]

where am ı wrong?

Onur Demir
  • 23
  • 4

1 Answers1

0

The problem is that lists hold pointers to objects that exist elsewhere in memory. That may sound complicated, so check this out:

a = [1, 2, 3]
b = a
b[0] = 5
print(a)
>>> [1, 5, 3]

What happened is that you didn't change b, you changed the list both a and b refer to!

So in your example, word is appended 3 times, but the list still "follows" the variable word. Instead try this:

from copy import copy

....
lst.append(copy(word))
Nathan
  • 3,558
  • 1
  • 18
  • 38
  • "The problem is that lists do not hold value-copied references as normal variables or function parameters do. Rather, they more accurately hold pointers to variables that exist elsewhere in memory." This is not true. List hold references to objects just like everything else in Python, regular variables, function parameters etc Nothing is ever value-copied in Python, copying always has to be explicit. And it doesn't "follow the variable word". Lists don't hold pointers to variables. Indeed, `list` objects are implemented with arrays of PyObject pointers, but they are pointers to *objects* – juanpa.arrivillaga Jan 27 '20 at 19:59
  • Also, `copy` is unnecessary here, you can just use `word.copy()` – juanpa.arrivillaga Jan 27 '20 at 20:01
  • With regards to the first point, I think you're right. I've rephrased it. Is this better @juanpa.arrivillaga? – Nathan Jan 27 '20 at 20:05
  • I used "followed the variable word" bevause I figured that would be easier to understand for a novice. – Nathan Jan 27 '20 at 20:06
  • I think copy.copy is the right choice because it allows to solve similar problems in the future – Nathan Jan 27 '20 at 20:06
  • 1
    Pointers to *objects* – juanpa.arrivillaga Jan 27 '20 at 20:08