0

Why it gives different outputs:

is there a difference between + and +=

def func1(lst1, lst2): lst1 += lst2 lst1 = [1, 2, 3] lst2 = ["a", "b"] func1(lst1, lst2) print(lst1) 

and

def func1(lst1, lst2): lst1 = lst1 + lst2 lst1 = [1, 2, 3] lst2 = ["a", "b"] func1(lst1, lst2) print(lst1) 

Thanks in advance

11
  • 1
    first program gives: [1,2,3] Second one : [1,2,3,'a','b','c'] Commented Jul 22, 2021 at 15:32
  • 1
    Does this answer your question? What exactly does += do in python? Commented Jul 22, 2021 at 15:32
  • 1
    @NirAlfasi Running in 3.8 I get two different outputs as well. Honest question, if those two operators are the same and it's just syntactic sugar (which was my assumption) why would we get two different responses from the print() of lst1? Commented Jul 22, 2021 at 15:33
  • 5
    Does this answer your question? Why does += behave unexpectedly on lists? Commented Jul 22, 2021 at 15:34
  • 1
    @NirAlfasi I removed that part, my bad. Commented Jul 22, 2021 at 15:38

3 Answers 3

10

The difference here is that += changes the initial list lst1. Whilst the lst1 = lst1 + lst2 creates a new list and rewrites local reference lst1 which does not affect global object lst1. If you try printing lst1 inside the functions, both cases would give you the same result.

Sign up to request clarification or add additional context in comments.

Comments

3

In your first example, you are passing a reference to lst1. Therefore, the increment affects the list that lst1 refers to.

In your second example, you're also passing a reference but the operation lst1 + lst2 creates a new list instance and lst1 subsequently points at that. Thus your original list is unaffected.

You need to decide if you really want lst1 modified or whether you want to know what the addition of the two lists looks like

Comments

3

A good IDE will give you a hint, like so:

Pycharm

If you recognize the dark grey color of lst1, move your mouse over it and it will give you a hint. Here, the problem is that the local variable is not used, as explained by @Yevhen Kuzmovych.

+= can have a different implementation than +. That's the case for lists: += modifies the list inplace whereas + gives you a new list and using the same name on the left side makes that not so obvious.

It also says that you have a naming issue, called shadowing. Did you expect lst1 from the outer scope to update, because it has the same name? If you thought that, you need to read about scope. If you know another programming language, you also want to understand the difference between pass by value, pass by reference and pass by assignment (Python).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.