I started to make a program that reorders the letters in a string
in different ways to practice some Python. I noticed that when using the .append()
method in a for loop, only the last iteration was getting appended again and again. I searched for an explanation but all I could
find was as solution to my issue but no good explanation to why it works.
My original code is:
def foo(word):
wordlist = list(word)
wordlist_copy = wordlist.copy()
combinations = []
for char in wordlist:
for i,let in enumerate(wordlist_copy):
wordlist_copy[i] = char
print(wordlist_copy)
combinations.append(wordlist_copy)
return combinations
The solution I found was to change line 11: combinations.append(wordlist_copy)
to combinations.append(list(wordlist_copy))
.
Why is it that using the list
method fixes my issue? I am already appending the wordlist_copy
list on each iteration of the loop, so I can’t understand how the method would do anything special here.