'How do I make a copy of a list in a function using slice in Python?
I have two lists where I want to pop elements from one list into the other one. I'm trying to use a [:] slice to make a copy since t don't want to modify the original list.
Why do I get an invalid syntax error?
def make_great(original_list[:], copy = []):
tmp = original_list.pop()
copy.append(tmp)
def show_magicians(ls = []):
for i in ls:
print ("our next magician is "+i+" !")
magician_list = ['daniel', 'david', 'sara', 'jose', 'maria', 'miriam']
show_magicians(magician_list)
Error message:
~/Python/function/ $ python p.py
File "/home/ubuntu/Python/function/p.py", line 2
def make_great(original_list[:], copy):
SyntaxError: invalid syntax
Solution 1:[1]
You have 2 options for making a shallow copy of a list in Python 3.
Either:
listB = listA[:]
...or...
listB = listA.copy()
Solution 2:[2]
You can not add [:] to the argument in the definition of make_great: An argument is just a name of a value, but not a computation. For example, you also could not write
def foo(bar + 1):
code...
Thus, you have to use the '[:]' at the place where you call make_great, like
make_great(list_to_be_copied[:], ...)
or you create the copy within make_great, like
def make_great(original_list, copy = []):
copy_of_orig_list = original_list[:]
...
Also, it seems that the argument copy shall take the result? In that case it would not make much sense to have it as a default argument. Also note the comment about default arguments with mutable values. You should consider returning the result.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Albert Winestein |
| Solution 2 | Dirk Herrmann |
