how can I avoid abusing lists?

Rob Cowie cowie.rob at gmail.com
Fri Jul 7 12:38:39 EDT 2006


Just forget the lists...

counters = {0:0, 1:0, 2:0, 3:0, 4:0}

def increment(value):
    counters[value] += 1

increment(1)
increment(1)
increment(3)
increment(4)

print counters[0]
>>> 0
print counters[1]
>>> 2
print coutners[2]
>>> 0
print counters[3]
>>> 1
print coutners[4]
>>> 1

The increment function should probably include a try:...except:
statement to catch KeyErrors that would arise if you passed a value
that is not a key in the counters dictionary.

Rob C




More information about the Python-list mailing list