What's the difference between [a] + [b] and [a].extend([b])?

强颜欢笑 提交于 2019-12-23 07:02:59

问题


There are 2 ways to merge lists together in Python:

  1. ['a', 'b', 'c'] + ['x', 'y', 'z']

  2. ['a', 'b', 'c'].extend(['x', 'y', 'z'])

What's the difference between the 2 methods?


What's the more Pythonic way of concatenating more than 2 lists?

['a', 'b', 'c'] + [1, 2, 3] + ['x', 'y', 'z']
gucci_list = ['a', 'b', 'c']
gucci_list.extend([1, 2, 3])
gucci_list.extend(['x', 'y', 'z'])

How about combining both?

['a', 'b', 'c'].extend([1, 2, 3] + ['x', 'y', 'z'])

回答1:


The first statement creates a new list out of two anonymous lists and stores it in the variable new_list:

new_list = ['a', 'b', 'c'] + ['x', 'y', 'z']
#['a', 'b', 'c', 'x', 'y', 'z']

The second statement creates an anonymous list ['a','b','c'] and appends another anonymous list to its end (now, the first list is ['a', 'b', 'c', 'x', 'y', 'z']). However, the list is still anonymous and cannot be accessed in the future. Since the method extend returns nothing, the value of the variable after the assignment is None.

new_list = ['a', 'b', 'c'].extend(['x', 'y', 'z'])
#None

The second statement can be made useful by first naming the list and then altering it:

old_list = ['a', 'b', 'c']
old_list.extend(['x', 'y', 'z']) # Now, the old list is a new list



回答2:


['a', 'b', 'c'] + ['x', 'y', 'z'] creates a new list.

['a', 'b', 'c'].extend(['x', 'y', 'z']) modifies the first list by adding the second list to it. Since the first list is not referenced by a variable, the resulting list wont be accessible anymore




回答3:


First one creates a new array from the two. Second one mutates the original list.



来源:https://stackoverflow.com/questions/51811937/whats-the-difference-between-a-b-and-a-extendb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!