-1

I study Python one week and get one problem. One list was edited in function. I got correct list when print the parameter, but original list is null.

name_list=['Jack','Lucky','Jimi','Andy']

def show_magicians(list):
    for name in list:
        print('Magician name is ' + name + '!')

def make_great(list):
    new_name_list=[]
    while list:
        temp_name = list.pop()
        new_name_list.append('the Great ' + temp_name)
    list = new_name_list[:]
    print(list)         # I get correct list.
    print(name_list)    # the list is null ??? 
  

make_great(name_list)

show_magicians(name_list)
wovano
  • 4,543
  • 5
  • 22
  • 49
Error05
  • 1
  • 1
  • 1
    Don't use the names of [built-ins](https://docs.python.org/3/library/functions.html) as variables. It shadows the built-in and can lead to all sorts of weird behavior. Plus, it makes your code difficult to read. – MattDMo Mar 07 '22 at 04:41
  • Hint: `list.pop()` removes items from that list. – MattDMo Mar 07 '22 at 04:42
  • You've come across a bit of [a confusing part of how python works](https://stackoverflow.com/questions/575196/why-can-a-function-modify-some-arguments-as-perceived-by-the-caller-but-not-oth), until you get the hang of it. – ramzeek Mar 07 '22 at 05:34
  • Does this answer your question? [Why can a function modify some arguments as perceived by the caller, but not others?](https://stackoverflow.com/questions/575196/why-can-a-function-modify-some-arguments-as-perceived-by-the-caller-but-not-oth) – wovano Mar 07 '22 at 08:41

3 Answers3

0

When you run your while loop it will empty your list thats why it it shows empty try to get list before pop out.

  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Mar 07 '22 at 06:15
0
name_list=['Jack','Lucky','Jimi','Andy']

def show_magicians(list):
   for name in list:
       print('Magician name is ' + name + '!')

def make_great(list):
    new_name_list=[]
    for name in list:
         new_name_list.append('the Great ' +name)
    list = new_name_list[:]
    print(list)         
    print(name_list)  
make_great(name_list)
show_magicians(name_list)  

Instead of deleting element just loop through each element and append to your new list(new_name_list)

zeeshan12396
  • 382
  • 1
  • 8
0

Thanks everyone. I got the answer. The parameter "list" is disconnected from the variable "name_list" when "list = new_name_list[:]". So there is right list in "list", but no list in "name_list".

Please refer to this article, https://nedbatchelder.com/text/names.html

Error05
  • 1
  • 1