Replace the last item in the list with another list

For example, I have two arrays a array1 and array2

 array1 = ['A', 'B', 'C', 'D', 'E', 'F',] array2 = ['G', 'H', 'I',]` 

Now I want the result to be

 array1 = ['A', 'B', 'C', 'D', 'E', 'G', 'H', 'I',] 

How to do it in python

+7
source share
4 answers
 >>> array1 = ['A', 'B', 'C', 'D', 'E', 'F'] >>> array2 = ['G', 'H', 'I'] >>> array1 = array1[:-1] + array2 >>> array1 ['A', 'B', 'C', 'D', 'E', 'G', 'H', 'I'] 
+17
source

To replace parts of a python list, you can use the slice assignment:

 >>> array1 = ['A', 'B', 'C', 'D', 'E', 'F'] >>> array2 = ['G', 'H', 'I'] >>> array1[-1:] = array2 >>> array1 ['A', 'B', 'C', 'D', 'E', 'G', 'H', 'I'] 

You can use the slice assignment to replace any part of the list, including inserting lists in which you do not replace existing elements:

 >>> array1[0:0] = ['1st', '2nd'] >>> array1 ['1st', '2nd', 'A', 'B', 'C', 'D', 'E', 'G', 'H', 'I'] 

Here the slice [0:0] selects the empty part of array1 and "replaces" it with new elements.

+16
source

When building arrays, itertools can be useful:

 import itertools array1 = itertools.chain(array1[:-1], array2) 

What is it.

Doc: http://docs.python.org/2/library/itertools.html#itertools.chain

0
source
 >>> array1.remove(array1[len(array1)-1]) >>> for i in array2: array1.append(i) 

Virtue Naive, but works.

-one
source

All Articles