-1

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'])
clickbait
  • 2,818
  • 1
  • 25
  • 61
  • 1
    The first creates a new list, while the second modifies the list on the left. – Patrick Haugh Aug 12 '18 at 19:01
  • 3
    For starters, the second option makes `new_list` equal `None` (did you try it?) because the function `extend` does not return anything. – DYZ Aug 12 '18 at 19:07
  • Lots of similar questions [1](https://stackoverflow.com/questions/3653298/concatenating-two-lists-difference-between-and-extend), and [2](https://stackoverflow.com/questions/2022031/python-append-vs-operator-on-lists-why-do-these-give-different-results), but haven't found a dupe – Sayse Aug 12 '18 at 19:08

3 Answers3

6

['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

Sunitha
  • 11,777
  • 2
  • 20
  • 23
4

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
DYZ
  • 55,249
  • 10
  • 64
  • 93
1

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

Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317