Python Forum
why in Python some time "n += 1" not like "n = n + 1" ?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
why in Python some time "n += 1" not like "n = n + 1" ?
#1
Hi All,

In the below example, why the result is different?
what the different between "n += [4, 5]" AND "n = n + [4, 5]"?

list1 = [1, 2, 3]
list2 = [1, 2, 3]

def proc1(n):
    n += [4, 5] 

def proc2(n):
    n = n + [4, 5]

proc1(list1)
print list1      #>>>> [1, 2, 3, 4, 5]
proc2(list2)
print list2      #>>>> [1, 2, 3]  !!!
Reply
#2
In proc2(), a new object n is created that is local to proc2() and then lost when the function is exited. In order to keep the result, you need to return it.
list1 = [1, 2, 3]
list2 = [1, 2, 3]
 
def proc1(n):
    n += [4, 5] 
 
def proc2(n):
    n = n + [4, 5]
    return n
 
proc1(list1)
print(list1)      #>>>> [1, 2, 3, 4, 5]
list2 = proc2(list2)
print(list2)      #>>>> [1, 2, 3]  !!!
Reply
#3
n += [4, 5] is an inline addition, which mutates the list.
n = n + [4, 5] creates a new list, which is assigned to n and n is local in the function.

Only the function itself can see the new list. One fix could be global, but this worsens it.

In normal cases you want to avoid side effects.
The side effect is, the modification of the list.
If you work later with numpy, you often modify the original data itself. But this is done for speed and memory consumption.

proc2 without side effects:

def proc1(n):
    return n + [4, 5]
It won't modify n, instead it creates a new list and return it.

In addition, n a bad name. Name it sequence or give it a name, which describes the content of the list.


def extend(sequence):
    return sequence + [4, 5]
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#4
In most languages this would be considered a bug.

DeaD_EyE is correct about side affects. Python is trying really hard to be a functional programming language with most types being immutable. If you write a function that changes a list it should create and return a new list. This is actually pretty efficient in python, so performance isn't a concern (usually). There is no meaningful way to document modified function arguments in python. Sure, you can write that in the docstring, but how many users read docstrings?
Reply
#5
TomToad, DeaD_EyE and deanhystad thank You alot
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to change UTC time to local time in Python DataFrame? SamKnight 2 1,528 Jul-28-2022, 08:23 AM
Last Post: Pedroski55
  Getting error in finding time.time() value in python Lakshana 1 2,464 Jan-11-2018, 07:07 AM
Last Post: wavic

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020