Reputation: 141
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']
Upvotes: 0
Views: 159
Reputation: 26
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)
Upvotes: 1
Reputation: 1260
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']
Upvotes: 1