Use the Counter class from collections :
>>> a = [('a', 'k1'), ('b', 'k2'), ('a', 'k2'), ('a', 'k1'), ('b', 'k2'), ('a', 'k1'), ('b', 'k2'), ('c', 'k3'), ('c', 'k4')] >>> from collections import Counter >>> c = Counter(a) Counter({('b', 'k2'): 3, ('a', 'k1'): 3, ('a', 'k2'): 1, ('c', 'k3'): 1, ('c', 'k4'): 1})
You can use c.items() to repeat the samples:
>>> for item in c.items(): ... print(item) ... (('a', 'k2'), 1) (('c', 'k3'), 1) (('b', 'k2'), 3) (('a', 'k1'), 3) (('c', 'k4'), 1)
The above code is Python 3. The Counter class is new in Python 2.7. Now you can arrange the elements in the desired order and convert them to a string, if necessary.