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:]
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.
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.
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!
The extend
method of list object does this, but at the end of the original list.
addition.extend(array)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With