how do i add a counter element to each recurring value in a tuple?

If you need the running count, you could use a defaultdict to keep it:

from collections import defaultdict

data = [('bike', '1'), ('bike', '2'), ('car', '3'), ('car', '4')]

result = []
counts = defaultdict(lambda: 1)
for ele in data:
    k, v = ele
    result.append((k, v, counts[k]))
    counts[k] = counts[k] + 1

print(result)

Output

[('bike', '1', 1), ('bike', '2', 2), ('car', '3', 1), ('car', '4', 2)]

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top