I'm currently reading Python Crash Course by Eric Matthes and doing some of the problem sets. One of them is giving me some difficulty and I was hoping someone could help me with it.
8-9. Magicians: Make a list of magician's names. Pass the list to a function called show_magicians(), which prints the name of each magician in the list.
8-10. Great Magicians: Start with a copy of your program from exercise 8-9. Write a function make_great() that modifies the list of magicians by adding the phrase the great to each magician's name. Call show_magicians() to see that the list has actually been modified.
magician_names=['Alice', 'Alex', 'Blake']
for magician in n:
To do this, you can append to a string and reassign to add words to the end of each element:
magician += " the great"
+= operator appends a string, then reassigns, which is equivalent to the following:
magician = magician + " the great"
Now, you can add this to a function like so:
def make_great(list_magicians): for i in range(len(list_magicians)): list_magicians[i] += " the great" make_great(magician_names) show_magicians(magician_names)
The output is:
Alice the great Alex the great Blake the great
How this works is that we use a 'counter' for loop, similar to the ones in languages like C, (you can also use
enumerate here), that loops through each element by using subscripts. Then it appends the string " the great" to all elements.
The reason why you cannot just do a simple
for-in loop and modify those values is because
for-in copies the value in the variable before
for magician in list_magicians: # magician is a temporary variable, does not hold actual reference to real elements
If they don't hold an actual reference, you cannot modify the reference, hence the reason you need to use counter loops to access the actual reference through subscript.