'What happen in the background: Reverse order without adding temporary variable

I'm trying to solve reverse order the string, then I'm coming with 2 solution that almost similar, but the result quite difference (I thought result should be same). I understand what happen in first_solution, but not in second_solution. Can someone explain to me why it is difference?

name='Michael'
name=list(name)
def first_solution(name):
    for i in range(0, int(len(name)/2)):
        name[i] = name[len(name)-1-i]
        name[len(name)-1-i] = name[i]
    return "".join(name)

name1='Michael'
name1=list(name1)

def second_solution(name1):
    for i in range(int(len(name1)/2)):
        name1[i], name1[len(name1)-1-i]=name1[len(name1)-1-i], name1[i]
    return "".join(name1)


print(first_solution(name))         #wrong_result: leahael
print(second_solution(name1))       #correct_result: leahciM



Solution 1:[1]

In the first case you're assigning the last letter to the first position, and then the letter in the first position (which is now the last letter) to the last position again. So after the first iteration `name[0] has become an "l", while name[-1] hasn't changed. You should use a temporary variable:

temp = name[len(name)-1-i]
name[len(name)-1-i] = name[i]
name[i] = temp

In the second case you are exploiting Python's capability to effectively swap two items as in a,b == b,a, so you don't need a temp

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 gimix