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
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)]
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.
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)]