-2

What is the actual difference between list1.append() and list1+list2 in python?? Along with this, why the following statement return NULL?

print(list1.append(list2))

{where list1 and list2 are 2 simple list}

Ivan Nevostruev
  • 28,143
  • 8
  • 66
  • 82
Dips yadav
  • 65
  • 1
  • 5
  • 1
    note that `.append` is much different then adding two lists together, however `.extend`ing one list by another is much more similar except it mutates the original list instead of returning a new one. – Tadhg McDonald-Jensen Jun 03 '16 at 03:42
  • `print` would return `None` in 3.x (in 2.x, it is a statement, so it does not return) **no matter what was printed**. Please make sure you understand the difference between displaying a value and returning it. – Karl Knechtel Sep 14 '22 at 14:42

4 Answers4

1

list.append() modifies the object and returns None.

[] + [] creates and "returns" new list.

https://docs.python.org/2.7/tutorial/datastructures.html#more-on-lists

Recommended reading: http://docs.python-guide.org/en/latest/writing/gotchas/

Dmitry Tokarev
  • 1,851
  • 15
  • 29
1

Returning None is a way to communicate that an operation is side-effecting -- that is, that it's changing one of its operands, as opposed to leaving them unchanged and returning a new value.

list1.append(list2)

...changes list1, making it a member of this category.


Compare the following two chunks of code:

# in this case, it's obvious that list1 was changed
list1.append(list2)
print list1

...and:

# in this case, you as a reader don't know if list1 was changed,
# unless you already know the semantics of list.append.
print list1.append(list2)

Forbidding the latter (by making it useless) thus enhances the readability of the language.

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
0
>>> a = [1,2,3]
>>> b = [4,5,6]
>>> a.append(b) # append just appends the variable to the next index and returns None
>>> print a
[1,2,3,[4,5,6]]
>>> a.extend(b) # Extend takes a list as input and extends the main list
[1,2,3,4,5,6]
>>> a+b # + is exactly same as extend
[1,2,3,4,5,6]
binu.py
  • 1,137
  • 2
  • 9
  • 20
0

When you print a function, you print what it returns and the append method does not return anything. However your list now has a new element. You can print the list to see the changes made.

list1 + list2 means that you combine 2 lists into one big list.

list1.append(element) adds one element to the end of the list.

Here's an example of append vs +

>>> a = [1,2,3]
>>> b = [4,5,6]
>>> a + b
[1, 2, 3, 4, 5, 6]
>>>
>>> a.append(b)
>>> a
[1, 2, 3, [4, 5, 6]]
ProfOak
  • 541
  • 4
  • 10