Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert the contents of one list into another

Tags:

python

list

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:] 
like image 460
Greg Avatar asked Apr 27 '11 14:04

Greg


People also ask

How do I add content from one list to another?

Use the extend() Method to Append a List Into Another List in Python. Python has a built-in method for lists named extend() that accepts an iterable as a parameter and adds it into the last position of the current iterable. Using it for lists will append the list parameter after the last element of the main list.

How do you append one list to another in Python?

Python's append() function inserts a single element into an existing list. The element will be added to the end of the old list rather than being returned to a new list. Adds its argument as a single element to the end of a list. The length of the list increases by one.


2 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!

like image 170
David Heffernan Avatar answered Sep 20 '22 17:09

David Heffernan


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

addition.extend(array) 
like image 28
philfr Avatar answered Sep 17 '22 17:09

philfr