Abd
Abd

Reputation: 119

What is the difference between two types of list additions in python?

I'm adding the list with itself in 2 ways. In output the memory location of updated list sometimes matches with parent list and sometimes not. May I know the explanation of this?

In 1st case I checked with + operator and assigned result to list reference. But in second case I used += operator.

1st case:

  x=[1,2,3]
  print(x, id(x))
  x+=x
  print(x, id(x))

output:

  [1, 2, 3] 88777032
  [1, 2, 3, 1, 2, 3] 88777032

2nd case:

  y=[1,2,3]
  print(y, id(y))
  y=y+y
  print(y, id(y))

output:

  [1, 2, 3] 88297352
  [1, 2, 3, 1, 2, 3] 88776904

Upvotes: 0

Views: 45

Answers (1)

Partho63
Partho63

Reputation: 3117

1st case: x += x just extends existing x by adding x

2nd case: y = y+y creates a new list by concatenating y two times (y and y) and then assigns the result to newly created object y

Upvotes: 1

Related Questions