0

What is the best way to add two array such as the ones below, where we only add the items which are at same index

a = ['a', 'b', 'c']
b = ['d', 'e', 'f']
a+b = ['ad', 'be', 'cf']

array size will be dynamic

Yash
  • 223
  • 2
  • 11

3 Answers3

4

You should use zip(). It links all elements with the same index

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

Output:

['ad', 'be', 'cf']

If there are more lists,

c=[''.join(x) for x in zip(a,b)]
3

You should use zip and str.join to be most flexible:

ab = [''.join(x) for x in zip(a, b)]

Or shorter, using map:

ab = [*map(''.join, zip(a, b))]

This works just as well for 3 or more lists.

user2390182
  • 72,016
  • 6
  • 67
  • 89
1

Using zip you can merge two lists. By unpacking this merged list containing tuples with items that share the same index in both lists you can simply concat these values. This gives the desired output you want.

add_a_b = [a_i + b_i for a_i, b_i in zip(a, b)]
chatax
  • 990
  • 3
  • 17