# [Tutor] New to this list ....

Peter Otten __peter__ at web.de
Fri Mar 30 18:19:49 CEST 2012

```Barry Drake wrote:

> On 30/03/12 16:19, Evert Rol wrote:
>> Not sure. In the sense that you can "optimise" (refactor) it in the same
>> way you could do with C. Eg: results = [0, 0, 0]
>> flags = [0, 1, 2, 3]
>> for flag in flags:
>>      results = getflag(flag, results)
>>
>
> That's exactly what I hoped for.  I hadn't realised I can initialise a
> list in one go - it seems that lists work a lot like the arrays I was
> used to in c.  Thanks to the others who took the time to answer.  Just
> now, Asokan's solution is a bit obscure to me - I'll work on that one,
> but the above is lovely and elegant; and easy to understand.  Someone
>
> def getflag(thisflag, results):
>      if (thisflag == 2):
>          results[0] += 1
>      elif (thisflag == 1):
>          results[1] += 1
>      elif (thisflag == 0):
>          results[2] += 1
>      return(results)
>
> In c, I would have used switch and case, but I gather there is no direct
> equivalent in Python ...   But it works as is.

Here is an alternative to if...elif..., a table (python list) that
translates from the flag to an index into the results table.

flag_to_result = [2, 1, 0]

def update_results(flag, results):
try:
results[flag_to_result[flag]] += 1
except IndexError:
pass # ignore flags other than 0, 1, 2

results = [0, 0, 0]
flags = [0, 1, 2, 3, 4, 3, 2, 1]
for flag in flags:
update_results(flag, results)
print results

The following operates on an even higher level:

from collections import Counter
flags = [0, 1, 2, 3, 4, 3, 2, 1]
counter = Counter(flags)
results = [counter[2], counter[1], counter[0]]
print results

```