I have created a function that takes a list as a parameter. It shuffles the list, replaces the first element and returns the 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
The shuffle has no impact on my question. However, I was surprised to see that the returned importedList 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 have found a workaround by copying the list within the function, but it 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 the 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'
See Question&Answers more detail:
os