Python: concatenate string variables of a list

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.

2 answers

  • answered 2018-01-11 19:50 Ajax1234

    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]
    

  • answered 2018-01-11 19:50 Don Peat

    List comprehension is more pythonic.

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

    Documentation