Nov. 7, 2020

Concatenate list elements using add, append, extend

List methods to concatenate new lists or iterables before or after original list. Append to embed new object as a nested element, and extend to convert iterable to a list of elements joined to the right.


Page contents

Add list of new elements to existing list

There are multiple ways to add a list of new elements, both before or after an already existing list.

Py3: Concatenate or add another list

data_list = [1, 2, 'end']

#    concatenate list and assign to new variable
#    add to right
right_list = data_list.__add__([3,4])    
#= [1,2,'end',3,4]

#    alternate form
right_list = data_list + [3, 4]
#= [1,2,'end',3,4]

#    to add to the left, both methods
left_list = [4, 5].__add__(data_list)
left_list = [4, 5] + data_list
#= [4,5,1,2,'end']

Using same token, multiple lists can be merged together.

Py3:Serially merge multiple lists

data1 = [1, 2, 3]
data2 = ['a', 'b']

#   concatenate 3 lists
new_list = data2 + data1 + data2           
#= ['a','b',1,2,3,'a','b']

Notes: New combined list

The add method with the '+' symbol concatenates two list end to end, creating a single list. Multiple concatenations can occur with a single statement creating very long merged lists.

Inplace concatenate iterables to list

Join any iterable to an existing list can be achieved inplace. When inplace addition of a list is done, it is not needed to assign the resulting list to a new list object. The old list itself is modified.

Py3: Inplace concat

data_list = [1,2,3]

#   string to letters
data_list += 'hello'
#= [1,2,3,'h','e','l','l','o']

#    append elements of tuple
data_list += (6, 7, 'hello')
#= [1,2,3,6,7,'hello']

#   the += notation is short of __iadd__
data_list.__iadd__((6,7,'hello'))
#= [1,2,3,6,7,'hello']

#    append keys of dict
a_dict = {4:'a', 5:'b'}
data_list += a_dict
#= [1,2,3,4,5]

#   range elements added
data_list += range(10,12)
#= [1,2,3,10,11]

Note that there are differences with the add and concat notations. The way concat is for list is defined is not equivalent for other languages like C/C++.

Py3: Differences between add and inplace concat

data_list = [1,2,3]

#   adding and reassigning works for lists
data_list = data_list + [4,5]           
#= [1,2,3,4,5]

#   adding does not work with other iterables
data_list = data_list + (4,5)
#= Type error

#   concat inplace works
data_list += (4,5)
#= [1,2,3,4,5]

#   summary: for list concatenation
#   a = a + b and a += b are not the same

The slice notations allows insertion of elements at any position within a list. Adding a second list to an existing one at any end is trivial, and operates inplace.

Py3: Merge with slices

data_list = [1,2,3]

#   using slice to extend at end
data_list[len(data_list):] = [4,5]
#= [1,2,3,4,5]

#   using slice to extend at front
data_list[:-len(data_list)] = [4,5]     
#= [4,5,1,2,3]

#   slice merge text
data_list[len(data_list):] = 'new'
#= [1,2,3,'n','e','w']

#   slice merge range
data_list[len(data_list):] = range(10,13)
#= [1,2,3,10,11,12]

Notes: Join an iterable

Concatenation method provides a way to add an iterable to a list to the right end. Adding required the new list to be reassigned to a variable, and only other lists can be added. The concat method is more versatile as it can convert any iterable into a list and add it to the end. Also the concat method is inplace, so the original variable is modified and it does not need to be reassigned.

Slice notation can be used to achieve same effect of concatenating two lists. It is a special case of inserting elements at any position with an existing list.The method allows the elements from new list or iterable to be inserted at the left or right. It is inplace, so the original list is modified with new elements.

Append single elements to the right

Append takes single elements and places them at the end of a list. The element is added inplace, and so the original list is modified. There is no need for ressignment of the final list to a new variable.

Py3: Built-in append for individual elements

data_list = ['ab','c']

#   add string to original
data_list.append('new')           
#= ['ab', 'c', 'new']

#   nest a whole list to original
data_list.append(['nested',1])       
#= ['ab','c',['nested',1]]

#   store a range object to original
#   range is not evaluated
data_list.append(range(1,5))
#= ['ab', 'c', range(1,5)]

Remember that the append statement is not unique, and same result can be achieved using iadd notation.

Py3: Equivalency for append statement

data_list = ['ab','c']

#   alternate way to achieve append
data_list += ['new element']
#= ['ab', 'c', 'new element']

Notes: Append single element

The append method nests an new element within a list. Single non iterable elements form new flat elements within list. Another iterable, or other objects like functions or classes are stored as nested items.

Extend list with elements of iterable

Extend is similar to iadd, and it achieves concatenation inplace.

Py3: Extend list with iterable

data_list = [1, 2]

#   extend(iterable) is same as  data_list += iterable
data_list.extend(['new','info']) 
#= [1, 2, 'new', 'info']

#   string is converted to letters
data_list.extend('new')
#= [1, 2, 'n', 'e', 'w']

#   range is converted to elements
data_list.extend(range(5, 7))
#= [1, 2, 5, 6]

Notes: Extending with another iterable

The extend method works similar to iadd by taking an iterable, converting it to a list, and joining it to the right of the existing list.

Concatenate a list of lists

Concatenate and flatten a list of list to single list and show relationship of append ane extend.

Py3: Concatenate list of lists

#   list of lists
lst_a = [[1,2,3],[4,5,6],['c','d']]

#   add to
lst_b = ['a', 'b']

[lst_b.extend(item) for item in lst_a]
print(lst_b)
#= ['a','b',1,2,3,4,5,6,'c','d']            

Notes: Extend each embedded iterable

Provided with a list of lists, each nested list is extended to the base list. This creates a one level flattened list.

Summary of concatenation methods

Both append and extend are inplace methods which add elements to the right (end) of existing list

Py3: Compare append and extend

lst_a = ['a', 'bc']
lst_b = [1, 2, [3, 4]]

#   append nests all elements
lst_a.append(lst_b)     
#= ['a', 'bc', [1,2,[3,4]]]

#  extend nests second level elements
lst_a.extend(lst_b)     
#= ['a', 'bc', 1, 2, [3,4]]

#   using comprehension to emulate extend
[lst_a.append(item) for item in lst_b]
print(lst_a)
#= ['a', 'bc', 1, 2, [3, 4]]

Functional summary of all five methods to add elements to a list.

Method/Statement Property
add (+ operator) joins elements of lists to right, creates new variable
iadd (+= operator) joins iterables to right, operates inplace
slice notation inserts elements of list anywhere, operates inplace
append inserts single elements to right, acts inplace
extend adds elements of iteravles to right, acts inplace

References

Popular content

python programming

Read and write lists with Pickle, Array and Pandas

python programming

Flatten nested list or generate blocks of nested lists

python programming

For loop and control statements

python programming

Clear list using inplace and standard methods

python programming

List comprehension with nested conditions

python programming

Concatenate list elements using add, append, extend

python programming

Enumerate and custom counters like skip and loop

python programming

Count number of elements, and memory allocated

python programming

Remove duplicate list elements

python programming

Statistics with numeric lists of integers, fractions, and decimals.

New content

python programming

Read and write lists with Pickle, Array and Pandas

python programming

Is element in list?

python programming

Dictionary merge common key groups

python programming

Packaging loops with zip

python programming

Concatenate list elements using add, append, extend

python programming

List comprehension with nested conditions

python programming

Flatten nested list or generate blocks of nested lists

python programming

Enumerate and custom counters like skip and loop

python programming

Range integer sequences

python programming

For loop and control statements