Refresh list content with another list in Python

advertisements

How would I extend the content of a given list with another given list without using the method .extend()? I imagine that I could use something with dictionaries.

Code

>>> tags  =['N','O','S','Cl']
>>> itags =[1,2,4,3]

>>> anew =['N','H']
>>> inew =[2,5]

I need a function which returns the refreshed lists

tags  =['N','O','S','Cl','H']
itags =[3,2,4,3,5]

When an element is already in the list, the number in the other list is added. If I use the extend() method, the the element N will appear in list tags twice:

>>> tags.extend(anew)
>>>itags.extend(inew)
>>> print tags,itags
     ['N','O','S','Cl','N','H'] [1,2,4,3,5,2,5]


You probably want a Counter for this.

from collections import Counter
tags = Counter({"N":1, "O":2, "S": 4, "Cl":3})
new = Counter({"N": 2, "H": 5})

tags = tags + new
print tags

output:

Counter({'H': 5, 'S': 4, 'Cl': 3, 'N': 3, 'O': 2})