0
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']

2
  • 7
    [x + y for x,y in zip(a, b)] Commented Aug 11, 2020 at 3:06
  • 2
    Or using string formatting f'{x}{y}' in place of x + y in the above. Commented Aug 11, 2020 at 3:08

2 Answers 2

1

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']
Sign up to request clarification or add additional context in comments.

Comments

1

You can use a enumerate function to elegantly solve your problem.

a = ['1', '2', '3']
b = ['a', 'b', 'c']
c = []
for idx, elem in enumerate(a):
  c.append(a[idx] + b[idx])
print(c)

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.