+
OperatorLet's say we have two lists, list1
and list2
. To combine (merge) these lists into a single list, we can use the +
operator:
1 2 3 4 5 6 | list1 = [ 'apple', 'orange' ] list2 = [ 'pineapple', 'blueberry' ] combined = list1 + list2 print( combined ) |
This code will output:
['apple', 'orange', 'pineapple', 'blueberry']
This works with any number of lists as well:
1 2 3 4 5 6 7 8 | list1 = [ 'apple', 'orange' ] list2 = [ 'pineapple', 'blueberry' ] list3 = [ 'grapefruit', 'mango' ] list4 = [ 'banana', 'strawberry' ] combined = list1 + list2 + list3 + list4 print( combined ) |
This code will output:
['apple', 'orange', 'pineapple', 'blueberry', 'grapefruit', 'mango', 'banana', 'strawberry']
+=
OperatorTo append (concatenate) the items in list2
to the end of list1
, we can use the +=
operator:
1 2 3 4 5 6 | list1 = [ 'apple', 'orange' ] list2 = [ 'pineapple', 'blueberry' ] list1 += list2 print( list1 ) |
This code will output list1
, which now includes the items from list2
:
['apple', 'orange', 'pineapple', 'blueberry']
We can combine the +=
and +
operators to combine more than two lists:
1 2 3 4 5 6 7 8 | list1 = [ 'apple', 'orange' ] list2 = [ 'pineapple', 'blueberry' ] list3 = [ 'grapefruit', 'mango' ] list4 = [ 'banana', 'strawberry' ] list1 += list2 + list3 + list4 print( list1 ) |
This code will output:
['apple', 'orange', 'pineapple', 'blueberry', 'grapefruit', 'mango', 'banana', 'strawberry']
.extend()
Alternatively, we can use the .extend()
method built into Python lists to append all items in list2
to list1
:
1 2 3 4 5 6 | list1 = [ 'apple', 'orange' ] list2 = [ 'pineapple', 'blueberry' ] list1.extend( list2 ) print( list1 ) |
Just as with the +=
operator, this code will output list1
, which now includes the items from list2
:
['apple', 'orange', 'pineapple', 'blueberry']
Because .extend()
is only able to take one list as an argument at a time, to extend by more than one list, we need to call .extend()
multiple times:
1 2 3 4 5 6 7 8 9 10 | list1 = [ 'apple', 'orange' ] list2 = [ 'pineapple', 'blueberry' ] list3 = [ 'grapefruit', 'mango' ] list4 = [ 'banana', 'strawberry' ] list1.extend( list2 ) list1.extend( list3 ) list1.extend( list4 ) print( list1 ) |
This code will output:
['apple', 'orange', 'pineapple', 'blueberry', 'grapefruit', 'mango', 'banana', 'strawberry']