Search code examples
pythonlistlist-comprehension

Join two lists using list comprehension


list1 = ['a', 'b', 'c', 'd']      
list2 = [1, 2, 3, 4]

# How can I get this result using list Comprehension
list3 = ['a', 'b', 'c', 'd', 1, 2, 3, 4]


list3 = [list1.append(x) for x in list2]
print(list3)

# returned
[None, None, None, None]

Solution

  • [*list1,*list2]
    
    #['a', 'b', 'c', 'd', 1, 2, 3, 4]
    

    not sure if this will be called list comp

    Edit:

    Technically this fits the definition of list comprehension

    list1 = ['a', 'b', 'c', 'd']      
    list2 = [1, 2, 3, 4]
    
    list3 = [x for x in (*list1,*list2)]
    #['a', 'b', 'c', 'd', 1, 2, 3, 4]
    

    but, why would you do this when you can simply do:

    list3=list1+list2