0

I can't find this question elsewhere on StackOverflow, or maybe my researching skills are not advanced enough, so I am asking now:

So I was playing around with Python today after not having touched it in a while and I found that the following snippet of code does not work:

>>> list1 = [1,2,3]
>>> list2 = [4,5,6]
>>> list3 = list1.append(list2)
>>> list3

Why does the last line not produce any results?

Also, I'm using Python 2.7.3, if that makes any difference

Edasaur
  • 397
  • 1
  • 8
  • 19
  • Looks like you want `list3 = list1 + list2` – Jon Clements Sep 19 '13 at 20:53
  • 1
    I agree with @JonClements -- Another option if you want to modify `list1` *in-place* then you can use `extend`: `list1.extend(list2)`. The benefit here is that `list2` doesn't have to be a list -- anything iterable will do. The downside is that you've just changed `list1` – mgilson Sep 19 '13 at 21:03
  • There are literally dozens of questions about how to concatenate lists. – Marcin Sep 19 '13 at 21:19

3 Answers3

9

list.append() operates in-place - it modifies the list it is called upon, and returns None.

>>> list1 = [1,2,3]
>>> list2 = [4,5,6]
>>> list1.append(list2)
>>> list1
[1, 2, 3, [4, 5, 6]]

So when you assign the returned value to list3, list3 is None, which the interactive shell does not print out implicitly like other results.

As a note, you might actually want list.extend() or +, depending on your use case.

Gareth Latty
  • 86,389
  • 17
  • 178
  • 183
5

list1.append(list2) modifies list1 and returns None, so list3 is None. None is not printed in interactive mode when it is the result of a statement.

kindall
  • 178,883
  • 35
  • 278
  • 309
5

In addition, in order to concatenate the lists you can do:

list3 = list1 + list2
anumi
  • 3,869
  • 2
  • 22
  • 22