Concatenating two lists - difference between '

2019-01-02 15:14发布

I've seen there are actually two (maybe more) ways to concatenate lists in Python: One way is to use the extend() method:

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

the other to use the plus(+) operator:

b += a

Now I wonder: Which of those two options is the 'pythonic' way to do list concatenation and is there a difference between the two (I've looked up the official Python tutorial but couldn't find anything anything about this topic).

标签: list python
7条回答
人气声优
2楼-- · 2019-01-02 15:45

You can chain function calls, but you can't += a function call directly:

class A:
    def __init__(self):
        self.listFoo = [1, 2]
        self.listBar = [3, 4]

    def get_list(self, which):
        if which == "Foo":
            return self.listFoo
        return self.listBar

a = A()
other_list = [5, 6]

a.get_list("Foo").extend(other_list)
a.get_list("Foo") += other_list  #SyntaxError: can't assign to function call
查看更多
登录 后发表回答