Reputation: 49
In Python 3, I'm currently trying to modify a list using a function. (By the way, VERY new to Python :) )
I'll show the directions for the problem, just as reference.
"Write a function called 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."
magicians = ['larry', 'mo', 'curly', 'nate']
def printing_magicians(names):
"""Printing the magicians names"""
for name in names:
print(name.title())
printing_magicians(magicians)
def make_great(names):
"""Adding 'the Great' to each magician"""
for name in names:
print(names + " the Great")
I'm not sure where to go from here. I don't understand what argument to call for the make_great() function, and then I don't understand how to apply a show_magicians() function to see the list that has been modified. Any help would be awesome! Thanks in advance.
Upvotes: 0
Views: 2672
Reputation: 1556
Here is the method in one line. The basic idea is to use list comprehension and modify all the elements of the list by slicing [:]
.
def make_great(names):
"""Adding 'the Great' to each magician"""
names[:] = [name + ' the Great' for name in names]
The show_magicians
function is to just print magicians
since magicians
variable is in the global scope.
def show_magicians():
print(magicians)
Example:
>>> make_great(magicians)
>>> show_magicians()
['larry the Great', 'mo the Great', 'curly the Great', 'nate the Great']
Upvotes: 1
Reputation: 159
You could also do something like this with newNames
defined globally:
newNames = []
def make_great(names):
for name in names:
name += " the Great"
newNames.append(name)
Then you can go ahead and print your new list by calling your function with newNames
as your argument.
Upvotes: 0
Reputation: 92440
It's idiomatic in Python to loop over lists with enumerate()
when you need the index. It will give you both the value and in the index into the list so you can:
def make_great(names):
for i, name in enumerate(names):
names[i] = f'{name} the Great'
Upvotes: 1
Reputation: 106598
To modify a list in-place, you should reference each item of the list by its index:
def make_great(names):
for i in range(len(names)):
names[i] += " the Great"
Upvotes: 3
Reputation: 1334
If you want the make_great
function to return the list you want, you can do:
def make_great(names):
return [name + " the Great" for name in names]
Upvotes: -1