How to insert the contents of one list into another

Question:

I am trying to combine the contents of two lists, in order to later perform processing on the entire data set. I initially looked at the built in insert function, but it inserts as a list, rather than the contents of the list.

I can slice and append the lists, but is there a cleaner / more Pythonic way of doing what I want than this:

array    = ['the', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']
addition = ['quick', 'brown']

array = array[:1] + addition + array[1:]
Asked By: Greg

||

Answers:

You can do the following using the slice syntax on the left hand side of an assignment:

>>> array = ['the', 'fox', 'jumped', 'over', 'the', 'lazy', 'dog']
>>> array[1:1] = ['quick', 'brown']
>>> array
['the', 'quick', 'brown', 'fox', 'jumped', 'over', 'the', 'lazy', 'dog']

That’s about as Pythonic as it gets!

Answered By: David Heffernan

The extend method of list object does this, but at the end of the original list.

addition.extend(array)
Answered By: philfr

insert(i,j), where i is the index and j is what you want to insert, does not add as a list. Instead it adds as a list item:

array = ['the', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']
array.insert(1,'brown')

The new array would be:

array = ['the', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']
Answered By: Gurjyot

Leveraging the splat operator / list unpacking for lists you can do it using

array    = ['the', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']
addition = ['quick', 'brown']

# like this
array2    = ['the', *addition, 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']

# or like this
array = [ *array[:1], *addition, *array[1:]]

print(array)
print(array2)

to get

['the', 'quick', 'brown', 'fox', 'jumped', 'over', 'the', 'lazy', 'dog']

The operator got introduces with PEP 448: Additional Unpacking Generalizations.

Answered By: Patrick Artner
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.