Python Recipe #1
I like Python because it is a flexible and extensible programming language. I wrote this little and short article to remind myself of the advantages and power of Python.
How you know, we can’t subtract elements of two lists. We’ll get an error.
>>> [1,2,3] - [1,2,3]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for -: 'list' and 'list'
Suppose you need to subtract elements of two lists using symbol -.
[1,2,3] - [1,2,3] = [1-1,2-2,3-3] = [0,0,0]
Or, if you need to sum two lists using symbol +.
[1,2,3] + [1,2,3] = [1+1,2+2,3+3] = [2,4,6]
So, we are going to create a subclass of Python list object called List, and override the __sub__() and __add__() methods of list. I know… there are many libraries and modules that do that in a better and efficient way. This article aims to show the power of Python.
First of all, we are going to develop a subclass called List from the Python object list.
#!/usr/bin/env python3.8class List(list):
def append(self,e):
if isinstance(e,list):
super(List,self).append(List(e))
else:
super(List,self).append(e) def __sub__(self,other):
r = List()
for i,v in enumerate(self):
r.append(v-other[i])
return r def __add__(self,other):
r = List()
for i,v in enumerate(self):
r.append(v+other[i])
return r
Now, we can create two lists as follows.
list_1 = List([1,2,3])
list_2 = List([1,2,3])
list_result = list_1 - list_2
print(list_result)
The output will be.
[0,0,0]
if you want to sum list_1 plus list_2 you just do:
list_1 = List([1,2,3])
list_2 = List([1,2,3])
list_result = list_1 + list_2
print(list_result)
The output will be.
[2,4,6]
That’s all for now. I’ll try to write this kind of short articles every time I need a recipe or a Tip related to Python.