Alex McClead Alex McClead - 2 months ago 64
Python Question

Python crash course 8-10

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.


And this is what I have for 8-9:

magician_names=['Alice', 'Alex', 'Blake']
def show_magicians(n):
for magician in n:
print (magician)

show_magicians(magician_names)


I just don't really know what to do for 8-10

Answer

To do this, you can append to a string and reassign to add words to the end of each element:

magician += " the great"

Here, the += 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 in:

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.

Comments