Python - Add Two Lists - If Number then Sum If String Then Concatenate

Python - Add Two Lists - If Number then Sum If String Then Concatenate

  • Python
  • 1 min read

This tutorial shows multiple examples of Python programs to add two lists, and if the list data type is a number, then sum up the value, and if a string then concatenate.

Example 1:

import operator
from functools import reduce

def concat_or_sum(*lists):
    return [reduce(operator.add, x) for x in zip(*lists)]

sum_list = concat_or_sum([2, 4, 't'], [5, 7, 't'], [10, 11, 't'])
print(sum_list)

sum_list = concat_or_sum([1, 'a', 'c'], [2, 'b', 'd'], [3, 'e', 'f'])
print(sum_list)

Output:

[17, 22, 'ttt']
[6, 'abe', 'cdf']

Example 2:

from operator import add
x = [2, 4, 'a']
y = [5, 7, 'b']
sum_list = list(map(add, x, y))
print(sum_list)

Output:

[7, 11, 'ab']

Example 3:

import operator
from functools import reduce

list1 = [2, 4, 'a']
list2 = [5, 7, 'b']

sum_list = [reduce(operator.add, x) for x in zip(list1, list2)]

print(sum_list)

Output:

[7, 11, 'ab']

See also: