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:

Vinish Kapoor

An Oracle Apex Consultant, Oracle ACE, and founder of foxinfotech.in and orclqa.com a question and answer forum for developers.

Leave a Reply