When you do x = x + "@gmail.com"
in the first version of the code, you're creating a new value and rebinding the name x
to refer to it. This has no effect on alist
, even though that's where the previous x
value came from.
When you do blist[x] = blist[x] + "@gmail.com"
on the other hand, you're explicitly modifying the list. You're rebinding blist[x]
to refer to a new value.
Note that with different list contents, you might have been able to make the first version of the code work, using "in place" modification. Strings are immutable though, so there are no in-place operations. However, if alist
contained mutable items such as list
s, code like x += ["foo"]
would extend the inner list in place. The +=
operator will attempt to do an in place addition if the type of the object supports it (by having an __iadd__
method). For types that don't support inplace operations though, it's just the same as x = x + y
, which will have the same issue you've encountered.