Four Methods For Merging Python 3 List

1. Use “+” Operator To Merge List Directly.

>>> list_1 = ['java','python','mysql']
>>> 
>>> list_2 = [100, 99, 101]
>>> 
>>> print(list_1 + list_2)
['java', 'python', 'mysql', 100, 99, 101]
>>> 
>>> print(list_2 + list_1)
[100, 99, 101, 'java', 'python', 'mysql']
>>> 

2. Use List’s extend Method.

The list’s extend method will extend current list with target list elements. The current list data is modified directly with the extended method, and the return value of the extend method is None.

>>> list_1 = ['java','python','mysql']
>>> 
>>> list_2 = [100, 99, 101]
>>> 
# extend list_1's elements to list_2
>>> list_2.extend(list_1)
>>> 
>>> print(list_2)
[100, 99, 101, 'java', 'python', 'mysql']

3. Use Slice.

len (list_1) represents where list_2 is to be inserted into list_1, then insert list_2 into list_1 at the end of list_1.

>>> list_1 = ['java','python','mysql']
>>> 
>>> list_2 = [100, 99, 101]
>>> 
>>> list_1_length = len(list_1)
>>> 
>>> list_1[list_1_length:list_1_length] = list_2
>>> 
>>> print(list_1)
['java', 'python', 'mysql', 100, 99, 101]

But you can also insert list_2 at any location in list_1 like below.

>>> list_1 = ['java','python','mysql']
>>> 
>>> list_2 = [100, 99, 101]
>>> 
>>> list_1[1:2] = list_2
>>> 
>>> print(list_1)
['java', 100, 99, 101, 'mysql']
>>> 

4. Use List’s append Method.

List’s append method will append the target list as a whole to original list. The target list is an element of original list.

>>> list_1 = ['java','python','mysql']
>>> 
>>> list_2 = [100, 99, 101]
>>> 
>>> list_1.append(list_2)
>>> 
>>> print(list_1)
['java', 'python', 'mysql', [100, 99, 101]]

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.