-2

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
jonrsharpe
  • 107,083
  • 22
  • 201
  • 376
  • 1
    Because that's not valid syntax _in the parameter list_. You're defining the name of the parameter, which can't contain [:]. If you want a copy, make it in the _body_ of the function. – jonrsharpe Feb 20 '22 at 11:17
  • 1) You should slice the list inside the function, not in the function's signature. 2) Be very careful with [mutable default arguments](https://stackoverflow.com/questions/1132941/least-astonishment-and-the-mutable-default-argument). – DeepSpace Feb 20 '22 at 11:17
  • Does this answer your question? [Python list copy](https://stackoverflow.com/questions/8951419/python-list-copy) – Dhana D. Feb 20 '22 at 11:23

2 Answers2

0

You have 2 options for making a shallow copy of a list in Python 3.

Either:

listB = listA[:]

...or...

listB = listA.copy()
Albert Winestein
  • 7,031
  • 2
  • 4
  • 14
0

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.

Dirk Herrmann
  • 5,101
  • 1
  • 18
  • 44