I used list, def. why li += [100,200] , and li = li + [100,200] is different

Rob Gaddi rgaddi at highlandtechnology.invalid
Mon Oct 23 12:38:20 EDT 2017


On 10/23/2017 09:29 AM, 임현준 wrote:
> I am a Korean student, and I am a beginner in English and Python.;(
> 
> I can't understand about this def
> 
> If I want to print
> 
> [1,2,3,4,5]
> [1,2,3,4,5,100,200]
> 
> I will make code like this, and I can understand code.
> 
> 
> def modify(li):
>       li += [100,200]
> 
> list = [1,2,3,4,5]
> print(list)
> modify(list)
> print(list)
> 
> 
> BUT, when I make code like this.
> 
> I will make code like this, and I can understand code.
> 
> 
> def modify(li):
>       li = li + [100,200]
> 
> list = [1,2,3,4,5]
> print(list)
> modify(list)
> print(list)
> 
> 
> 
> python print
> 
> [1,2,3,4,5]
> [1,2,3,4,5]
> 
> why 'li+= [100,200]'and 'li = li + [100,200]' 's print is different
> please help me
> 

Lists are mutable, they can be changed.  Your call to += is equivalent 
to a call to li.extend([100, 200]), which changes the single existing 
object pointed to by the "li" reference.  The second time, however, you 
take the existing value that "li" refers to [1,2,3,4,5], create a new 
object that is ([1,2,3,4,5] + [100,200]), and reassign the local 
reference "li" to point to that new object.  Then your function ends, 
"li" goes out of scope, nothing points to that newly created object and 
it gets lost.

-- 
Rob Gaddi, Highland Technology -- www.highlandtechnology.com
Email address domain is currently out of order.  See above to fix.



More information about the Python-list mailing list