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.

Ry-
  • 218,210
  • 55
  • 464
  • 476
Tho Pham
  • 11
  • 1

2 Answers2

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]
Ajax1234
  • 69,937
  • 8
  • 61
  • 102
  • 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... – Tho Pham Jan 11 '18 at 19:58
1

List comprehension is more pythonic.

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

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

Documentation

Don
  • 3,876
  • 10
  • 47
  • 76