0

I wrote the code on my own for this task as shown below:

def showmagicians(magician_names):
    for name in magician_names:
        print(name)

def make_great(magician_names):
    the_greats = []
    **for name in magician_names:**
        the_great = name +'_the_great'
        pop_name = magician_names.pop()
        the_greats.append(the_great)
    for the_great in the_greats:
        magician_names.append(the_great)
    return magician_names

magician_names = ['harry','david']
showmagicians(magician_names)
make_great(magician_names)
print(magician_names)

**Output:
harry
david
['harry', 'harry_the_great']**

I didn't use 'while' statement in the ‘make_great function’, I used 'for' statement, and the output is wrong. But I can't see there is a difference between the two.

The task requires us to output the 'magician_names' with 'the great' suffix. The code provided by the book is listed here: https://ehmatthes.github.io/pcc/solutions/chapter_8.html#8-6-city-names Can someone tell me what's the difference???

han Lin
  • 1
  • 1

1 Answers1

0

You are iterating on magician_names so going forward and pop from it (remove item), so backwards

  • list is ['harry', 'david'] cursor on harry
  • pop so remove david
  • cursor have nowhere else to move, you just iterate on harry

Make your method make_great return the the_greats list, assign it to a variable in the main code and you're good

def make_great(magician_names):
    the_greats = []
    for name in magician_names:
        the_great = name + '_the_great'
        the_greats.append(the_great)
    return the_greats


magician_names = ['harry', 'david']
print(magician_names)  # ['harry', 'david']
magician_names = make_great(magician_names)
print(magician_names)  # ['harry_the_great', 'david_the_great']

The list comprehension version

def make_great(magician_names):
    return [name + '_the_great' for name in magician_names]
azro
  • 53,056
  • 7
  • 34
  • 70