2

So I have 2 lists:

L1 = ['a', 'b', 'c', 'd']
L2 = ['1', '2', '3', '4']

I need my result to look like this:

['a1', 'b2', 'c3', 'd4']

I used a for loop, but I can't seem to get it right. This is what I did:

L3 = []
L1 = ['a', 'b', 'c', 'd']
L2 = ['1', '2', '3', '4']
for i in range(len(L1)):
     L3 += L1[i] + L2[i]
print(L3)

My results end up looking like:

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

And that's all I have. Any help would be greatly appreciated!

5 Answers 5

7

The zip function produces an iterator that returns tuples from each of its arguments in sequence:

L3 = [x + y for x, y in zip(L1, L2)]

Documentation: https://docs.python.org/3/library/functions.html#zip

4

L3 += L1[i] + L2[i] is equivalent to L3.extend(L1[i] + L2[i])

L1[i] + L2[i] is a string like 'a1'. extend expects an iterable, and it will append each of its elements to the list. So, it iterates over your 'a1' string and appends to the list the elements 'a' and '1'.

You want to append the string instead:

L3.append(L1[i] + L2[i])

As noted by Mark Tolonen,

L3 += [L1[i] + L2[i]]

also works. It is equivalent to L3.extend([L1[i] + L2[i]]), so for example L3.extend(['a1']). In this case, extend will append the only element of the list it receives as parameter, 'a1', to L3.

2
  • @MarkTolonen That's right, I added it to the answer. Feb 18, 2018 at 23:11
  • 1
    While it is true that L3 += [L1[i] + L2[i]] also works, I would argue that it is less clear than L3.append(L1[i] + L2[i]). Feb 18, 2018 at 23:32
1

You can just change the += operation to .append:

for i in range(len(L1)):
    L3.append(L1[i] + L2[i])
0
L3 = []
L1 = ['a', 'b', 'c', 'd']
L2 = ['1', '2', '3', '4']
for i in range(len(L1)):
     L3.append(str(L1[i])+str(L2[i]))
print(L3)
0

Similar to another answer using list comprehension:

L3 = [L1[i]+L2[i] for i in range(len(L1))]

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.