The be more accurate when do
func-1 you're passing the reference of the list,so the function modifies the original list.
func-2 you're passing a
To give an other example,which also is a common mistake(modify a list you loop over) why is
f(b[:]
you are making a copy
of b
then pass if to f
.func-1 you're passing the reference of the list,so the function modifies the original list.
func-2 you're passing a
shallow copy
of the list to the function,so the original list remains unchanged.To give an other example,which also is a common mistake(modify a list you loop over) why is
albatross
in output?words = ['eagle', 'albatross', 'mouse', 'dog', 'tiger'] for w in words: if len(w) > 3: words.remove(w) print(words)
Output:['albatross', 'dog']
If loop over copy
of words then it work.words = ['eagle', 'albatross', 'mouse', 'dog', 'tiger'] for w in words[:]: if len(w) > 3: words.remove(w) print(words)
Output:['dog']
Or better do not use copy
or remove
at all.words = ['eagle', 'albatross', 'mouse', 'dog', 'tiger'] words = [w for w in words if len(w) <= 3] print(words)
Output:['dog']