On 2017-10-23 17:29, 임현준 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
In both cases, you're binding a list to the local name "li".
However, in the first example:
li += [100,200]
it's doing this:
li = li.__iadd__([100,200])
The __iadd__ method is modifying the list li and then returning that
modified list.
The list that was passed in has been modified.
In the second example:
li = li + [100,200]
it's doing this:
li = li.__add__([100,200])
The __add__ method is creating a new list and then returning that new list.
The local name "li" now refers to a new list, not the list that was
passed in. When the function returns, the local name "li" is forgotten,
and the new list that "li" referred to is discarded because there are no
other references to it.
--
https://mail.python.org/mailman/listinfo/python-list