Change List with a python function

Asked

Viewed 507 times

0

I’m developing some book exercises "Intensive Course of Python" but I stopped in the proposed 8.10 exercise:

EX: 8.10 - Great magicians: Start with a copy of your program from Exercise 8.9. Write a function named make_great() that modifies the list of magicians adding the expression the Great to each magic. Call show_magicians() to see if the list has actually been modified.

My 8.9 exercise program went like this:

  print("===================== EX-01 ================")
  magicos = ["Mario", "João", "Maria"]
  '''Exibe uma saudação aos magicos'''
  def nomes_dos_magicos(nome):
      for magico in magicos:
          print("Olá,", magico)

saudacao = nomes_dos_magicos(magicos)

My difficulty is in storing that new "Big" value before the names inside the original list and not just in the function

2 answers

0


You can also use the function range:

print("===================== EX-01 ================")
magicos = ["Mario", "João", "Maria"]
'''Exibe uma saudação aos magicos'''
def nomes_dos_magicos():
    for i in range(len(magicos)):
        magicos[i] = "O Grande " + magicos[i]

nomes_dos_magicos()
print(magicos)

Or, if you want to use comprehensilist on, the function is thus:

def nomes_dos_magicos():
    global magicos
    magicos = ["O Grande " + magico for magico in magicos]

Note that in practice it is unnecessary to define a function if you use comprehensilist on in the latter case. But, as it is an exercise, this is it.

0

For this, it is necessary to change the value of the variable mágicos when calling the function nomes_dos_magicos.

Here I use the function enumerate to access the list entry when we are doing the for loop:

print("===================== EX-01 ================")
magicos = ["Mario", "João", "Maria"]
'''Exibe uma saudação aos magicos'''
def nomes_dos_magicos(nome):
  for i, nome in enumerate(magicos):
      magicos[i] = "O Grande " + nome

nomes_dos_magicos(magicos)
print(magicos)
  • Ahh yes, in case that change to "The great" would not be applied to the original list definitively, and yes, in the function call, for example: when I called the greeting function of the previous exercise that modification should also be there because the original list has been modified

Browser other questions tagged

You are not signed in. Login or sign up in order to post.