1

I am new to python and can't figure out why adding to a list with the + sign creates a new list with a different id but using .append adds elements to a list at the original id.

The list and its id:

>>> list = [1,2,3]
>>> id(list)
140619372689160

Adding to the list using + makes a new list:

>>> list + [4,5,7]
[1, 2, 3, 4, 5, 7]

Print list again does not include addition:

>>> print(list)
[1, 2, 3]

The address of the list is the same:

>>> id(list)
140619372689160

Why does adding to the list create a new list and not add to the list at that address?

Ry-
  • 218,210
  • 55
  • 464
  • 476
cturner
  • 11
  • 1
  • you're not assigning the new list to `list` when you perform the addition. you need to declare a new variable, or use list again. BTW, don't use `list`, it's a builtin – PRMoureu Jul 01 '17 at 00:46
  • `2 + 2` adds two integers to make a new integer. `[2] + [2]` adds two lists to make a new list. Why would `+` modify its operands? You can use `.extend()` to add all elements of a sequence to a list. – Ry- Jul 01 '17 at 00:47

1 Answers1

-1

what you want to do is :

list += [4,5,7]

or

list = list + [4,5,7]

like that you assign the new created list to your actual list

quick example:

l = [1,2,3]
l += [4,5,6]
print(l) # returns [1,2,3,4,5,6]
Rayhane Mama
  • 2,374
  • 11
  • 20