Python - Extending a list directly results in None, why?

后端 未结 2 1681
轮回少年
轮回少年 2020-12-21 19:27
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\         


        
相关标签:
2条回答
  • 2020-12-21 19:53

    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.

    0 讨论(0)
  • 2020-12-21 20:04

    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)
    
    0 讨论(0)
提交回复
热议问题