Several methods are
- Using Numpy
import numpy as np
x = np.array([2,3,3])
y = np.array([1,2,6])
print(type(x)) # <class 'numpy.ndarray'>
print(type(y)) # <class 'numpy.ndarray'>
print(x+y) # [3 5 9]
print(type(x+y)) # <class 'numpy.ndarray'>
In the above code, You can see input and output are NumPy array formats.
import numpy as np
list1=[4,2,2,5]
list2=[2,1,6,7]
print(type(list1)) # <class 'list'>
print(type(list2)) # <class 'list'>
print(np.add(list1,list2)) # [ 6 3 8 12]
print(type(np.add(list1,list2))) # <class 'numpy.ndarray'>
Here, Input and output are in different formats.
- Using Numpy add
import numpy as np
list1=[3, 1, 4]
list2=[0, 9, 7]
print(type(list1)) # <class 'list'>
print(type(list2)) # <class 'list'>
print(np.add(list1, list2).tolist()) # [3, 10, 11]
print(type(np.add(list1, list2).tolist())) # <class 'list'>
In this example, explicitly we are converting NumPy array to list type using to_list()
- Using Map and Lambda
list1=[1, 3, 3]
list2=[3, 6, 8]
print(map(lambda x,y:x+y, list1, list2)) # <map object at 0x7fea235260a0>
print(list(map(lambda x,y:x+y, list1, list2))) # [4, 9, 11]
- Using zip and list comprehension
list1=[3, 1, 3]
list2=[1, 1, 3]
print(type(list1)) # <class 'list'>
print(type(list2)) # <class 'list'>
print(x + y for x, y in zip(list1, list2)) # <generator object <genexpr> at 0x7f755307b6d0>
print(list(x + y for x, y in zip(list1, list2))) # [4, 2, 6]
print(type([x + y for x, y in zip(list1, list2)])) # <class 'list'>
print(sum(x) for x in zip(list1, list2)) # <generator object <genexpr> at 0x7f4c623e76d0>
print(list(sum(x) for x in zip(list1, list2))) # [4, 2, 6]
print(type([sum(x) for x in zip(list1, list2)])) # <class 'list'>
- Using Map and operator.add
from operator import add
list1=[3, 1, 3]
list2=[1, 1, 3]
print(list(map(add, list1, list2))) # [4, 2, 6]