Reputation: 31
I am working through Python: Crash Course and have got to a problem that I am somewhat solving, but there is probably a better way.
I am trying to modify this list:
magicians = ['Houdini', 'Copperfield', 'Blaine']
by adding 'The Great ' before each item in the list to get:
magicians = ['The Great Houdini','The Great Copperfield', 'The great Blaine']
The books says I am supposed to use a for loop and function to do this, and am supposed to directly modify the list. I found an ugly solution, but was hoping there was a better way to solve it. Here is what I came up with.
def make_great(magic):
""" add 'the great' to a list of magicians"""
new_magic= []
for names in magic:
names = 'the great ' + names
new_magic.append(names)
global magicians
magicians = new_magic
make_great(magicians)
print(magicians)
Thanks for your help!
Upvotes: 0
Views: 141
Reputation: 2347
You have three requirements: 1) Directly modify the original list, 2) Use a function, and 3) Use a for
loop. It's a technicality, but unlike the previous answers the following approach does not create a new list first, choosing instead to update each item in the original list itself. So, here's how you can satisfy all of the requirements:
def prefixNames(alist):
for i,name in enumerate(alist):
alist[i] = " ".join(("The Great", name))
# example:
magicians = ['Houdini', 'Copperfield', 'Blaine']
prefixNames(magicians)
print(magicians)
['The Great Houdini', 'The Great Copperfield', 'The Great Blaine']
Upvotes: 2
Reputation: 55479
Here's how to do this modification to the original list using a function and a traditional for
loop.
To modify the original list object we can use a slice assignment: magic[:] = new_magic
. You should not be trying to modify the global magicians
list, you need to work with the magic
list object that's passed to the make_great
function.
def make_great(magic):
""" add 'The great ' to a list of magicians"""
new_magic = []
for name in magic:
new_magic.append('The great ' + name)
magic[:] = new_magic
magicians = ['Houdini', 'Copperfield', 'Blaine']
make_great(magicians)
print(magicians)
output
['The great Houdini', 'The great Copperfield', 'The great Blaine']
We can make the function more compact (and slightly more efficient) by using a list comprehension.
def make_great(magic):
""" add 'The great ' to a list of magicians"""
magic[:] = ['The great ' + name for name in magic]
Upvotes: 2
Reputation: 56886
How about this?
magicians = ['Houdini', 'Copperfield', 'Blaine']
print(['The Great ' + x for x in magicians])
Output:
['The Great Houdini', 'The Great Copperfield', 'The Great Blaine']
Upvotes: 1