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 lists, 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

Popular posts from this blog

java - Run spring boot application error: Cannot instantiate interface org.springframework.context.ApplicationListener -

reactjs - React router and this.props.children - how to pass state to this.props.children -

Excel VBA "Microsoft Windows Common Controls 6.0 (SP6)" Location Changes -