1
x=[1,2,3]
x.extend('a')

Output:

x is [1,2,3,'a']

But when I do the following:

[1,2,3].extend('a')

Output:

None

Why does extend work on a list reference, but not on a list?

2nd Part:

I found this because I was trying to append a listB to a listA while trying to extend listC to listB.

listA.append([listB[15:18].extend(listC[3:12])])

Supposing lists cannot be directly appended / extending. What is the most popular work around form for resolving this issue?

Community
  • 1
  • 1
Phoenix
  • 4,386
  • 10
  • 40
  • 55
  • `None` is the output of print statement , if you are using `print [1,2,3].extend('a')`. Because return type of `extend` is `None` – Nishant Nawarkhede Feb 27 '14 at 11:43
  • 2
    It is a convention in Python that methods that mutate sequences return `None`. More [here](http://stackoverflow.com/questions/9299919/add-number-to-set/9300257#9300257). – Steven Rumbalski Feb 27 '14 at 11:52

2 Answers2

4

list.extend modifies the list in place and returns nothing, thus resulting in None. In the second case, it's a temporary list that is being extended which disappears immediately after that line, while in the first case it can be referenced via x.

to append a listB to a listA while trying to extend listC to listB.

Instead of using extend, you might want to try this:

listA.append(listB[15:18] + listC[3:12])

Or do it in multiple simple lines with extend if you want to actually modify listB or listC.

YS-L
  • 14,358
  • 3
  • 47
  • 58
0

extend will extend list it self. Return type of that method is None

If you want to union 2 list and add that list to another list then you have to use another way to add.

listB[15:18] = listC[3:12]
listA.extend(listB)
Nilesh
  • 20,521
  • 16
  • 92
  • 148