Search code examples
pythonstringlistconcatenation

Concatenate elements from two lists into a third one in python


a = ['1', '2', '3']
b = ['a', 'b', 'c']
c = []

What can I do to get the third list to be the concatenation of the corresponding elements from lists a and b, as in:

c = ['1a', '2b', '3c']


Solution

  • Here is a simple while loop to do the trick:

    a = ['1', '2', '3']
    b = ['a', 'b', 'c']
    c = []
    
    counter = 0
    while counter < len(a):
        c.append(a[counter] + b[counter])
        counter += 1
    
    print(c)
    

    Obviously, there are more elegant methods to do this, such as using the zip method:

    a = ['1', '2', '3']
    b = ['a', 'b', 'c']
    c = [x + y for x,y in zip(a, b)]
    
    print(c)
    

    Both methods have the same output:

    ['1a', '2b', '3c']