I created a function that takes a list as a parameter. It shuffles the list, replaces the first element, and returns a new list.
import random firstList=["a","b","c","d","e","f","g","h","i"] def substitution(importedList): random.shuffle(importedList) importedList[0]="WORD" return importedList
Shuffling does not affect my question. However, I was surprised to see that the returned importList overwrites the original firstList.
>>> firstList ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'] >>> substitution(firstList) ['WORD', 'a', 'b', 'd', 'i', 'c', 'g', 'e', 'h'] >>> firstList ['WORD', 'a', 'b', 'd', 'i', 'c', 'g', 'e', 'h']
I found a workaround by copying the list inside the function, but this seems inefficient.
import random firstList=["a","b","c","d","e","f","g","h","i"] string="a" def substitutionandcopy(importedList): copiedList=importedList[:] random.shuffle(copiedList) copiedList[0]="WORD" return copiedList
My question is: why does the function replace firstList? This would not happen if it were a string, for example.
string="a" def substituteString(foo): foo='b' return foo
>>> string 'a' >>> substituteString(string) 'b' >>> string 'a'