oursolutionarchitectoursolutionarchitect
  • Python Questions and Answers
  • Python - Programming Examples
  • Python - Quick Guide
  • Python - Useful Resources
  • Python - Discussion
    • Selected Reading
    • Q&A

    Python - Join Lists


    In Python, List is classified as a sequence type object. It is a collection of items, which may be of different data types, with each item having a positional index starting with 0. You can use different ways to join two Python lists.

    All the sequence type objects support concatenation operator (+), with which two lists can be joined.

    Example

    L1 = [10,20,30,40]
    L2 = ['one', 'two', 'three', 'four']
    L3 = L1+L2
    print ("Joined list:", L3)
    

    It will produce the following output

    Joined list: [10, 20, 30, 40, 'one', 'two', 'three', 'four']
    

    Join Python Lists Using Augmented Concatenation Operator

    You can also use the augmented concatenation operator with "+=" symbol to append L2 to L1

    Example

    L1 = [10,20,30,40]
    L2 = ['one', 'two', 'three', 'four']
    L1+=L2
    print ("Joined list:", L1)
    

    The same result can be obtained by using the extend() method. Here, we need to extend L1 so as to add elements from L2 in it.

    L1 = [10,20,30,40]
    L2 = ['one', 'two', 'three', 'four']
    L1.extend(L2)
    print ("Joined list:", L1)
    

    Join Python Lists by Appending Items

    To add items from one list to another, a classical iterative solution also works. Traverse items of second list with a for loop, and append each item in the first.

    Example

    L1 = [10,20,30,40]
    L2 = ['one', 'two', 'three', 'four']
    
    for x in L2:
       L1.append(x)
       
    print ("Joined list:", L1)
    

    Join Python Lists using List Comprehension

    A slightly complex approach for merging two lists is using list comprehension, as following code shows −

    Example

    L1 = [10,20,30,40]
    L2 = ['one', 'two', 'three', 'four']
    L3 = [y for x in [L1, L2] for y in x]
    print ("Joined list:", L3)