python - Why do these two forms of iteration produce different results? -
alist = ['1', '2', '3'] blist = alist[:] x in alist: if not "@gmail.com" in alist: x = x + "@gmail.com" x in range(len(blist)): if not "@gmail.com" in blist[x]: blist[x] = blist[x] + "@gmail.com"
the first block of code not implement need, yet second 1 does.
what difference between these 2 blocks of code?
when x = x + "@gmail.com"
in first version of code, you're creating new value , rebinding name x
refer it. has no effect on alist
, though that's previous x
value came from.
when blist[x] = blist[x] + "@gmail.com"
on other hand, you're explicitly modifying list. you're rebinding blist[x]
refer new value.
note different list contents, might have been able make first version of code work, using "in place" modification. strings immutable though, there no in-place operations. however, if alist
contained mutable items such list
s, code x += ["foo"]
extend inner list in place. +=
operator attempt in place addition if type of object supports (by having __iadd__
method). types don't support inplace operations though, it's same x = x + y
, have same issue you've encountered.
Comments
Post a Comment