0

I'm trying to change a given list, table, replacing its values when in the same position of another list, word, is a string and them print it as a string.

That is working. The problem is that when I try to print word after executing the function, the list is changed.

def table_printer ( board, text):
    returned_table = ''
    copy = text
    for i in text:
        if type(i) == str:
            board[ copy.index(i) ] = i
            copy[ copy.index(i) ] = 1
    for i in board: 
        returned_table += ' ' + i + ''
    return returned_table

table = ['_','_','_','_','_']
word = [ 'p', 1, 'a', 3, 'a' ]

printed = table_printer( table, word )

print(printed)
print(word)

The output I'm getting

p 1 a 3 a
[1, 1, 1, 1, 1]

The output I'm expecting

p 1 a 3 a
[ 'p', 1, 'a', 3, 'a' ]
  • `copy = text` doesn't make a copy. Both variables are references to the same list. Use `copy = text.copy()` – Barmar Jun 06 '22 at 23:47
  • `board` is a reference to the same list as `table`. Modifying one modifies the other. Use `board = board.copy()` to make a copy. – Barmar Jun 06 '22 at 23:49
  • Note that `copy.index(i)` will not be the current index of the loop if there are duplicate values in `copy`. Use `for index, i in enumerate(text):` to get the indexes properly. – Barmar Jun 06 '22 at 23:50

0 Answers0