1

I am trying to modify all of the elements of the list in Python:

magicians = ['harry potter', 'scamander', 'snape']

for magician in magicians:      
    magician = 'the Great ' + magician

print(magicians)

but it returns the original list:

['harry potter', 'scamander', 'snape']

Can you please kindly explain this to me step-by-step? This may be a very stupid question you have ever seen. I'm truly sorry for that.

0

2 Answers 2

4

You are only mutating the element in the loop-scope. Instead, reassign using the element index:

magicians = ['harry potter', 'scamander', 'snape']

for i, magician in enumerate(magicians):      
   magician = 'the Great ' + magician
   magicians[i] = magician

print(magicians)

Output:

['the Great harry potter', 'the Great scamander', 'the Great snape']

However, it is much shorter to use list comprehension:

magicians = ['harry potter', 'scamander', 'snape'] 
new_magicians = ['the Great {}'.format(i) for i in magicians]

Output:

['the Great harry potter', 'the Great scamander', 'the Great snape']

In the scope of the problem, a loop is not even necessary:

final_data = ("the Great {}*"*len(magicians)).format(*magicians).split('*')[:-1]
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much for your time on my stupid question. I just knew the enumerate() function through your question. Can you please kindly explain a little bit further the underlying process under the for loop in my question? The dumb me just thought that the for loop will loop through the list to pick every element and assign it to magician variable. Really thank you...
1

List comprehension is more pythonic.

magicians = ['harry potter', 'scamander', 'snape']

great_magicians = ['the Great {}'.format(magician) for magician in magicians]

Documentation

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.