1

Let's say I have to loop over something and keep counters of various characteristics as the loop progresses. Before the loop, I could create these various counter variables with initial values.

count1 = 0
count2 = 0

for index in range(0, 10):
    count1 += 1
    count2 += 2

print count1, count2

Alternatively, I could create the counter variable when it is first actually used by using a conditional statement in the loop that creates the variable if it doesn't exist and then the variable is incremented.

for index in range(0, 10):
    if "count1" not in locals():
        count1 = 0
    if "count2" not in locals():
        count2 = 0        
    count1 += 1
    count2 += 2

print count1, count2

Is there a more compact or efficient way to do this?

d3pd
  • 7,935
  • 24
  • 76
  • 127
  • 2
    Well, in the cases you list above, you could do `count1 = sum(1 for _ in range(10)` and `count2 = sum(2 for _ in range(10)`. – Morgan Thrapp Oct 07 '15 at 15:48
  • 1
    You can put them on one line if you want: `count1, count2 = 0, 0` – vaultah Oct 07 '15 at 15:49
  • 1
    or count1 = count2 = 0 – Rolf of Saxony Oct 07 '15 at 15:51
  • @MorganThrapp My variables are intended to be representative examples; I'm counting many things in the loop. The point of the two counters was to show that they are not both trivial and that there are multiple counters. – d3pd Oct 07 '15 at 15:53
  • Then have a dictionary or list of counters, rather than separate names. It will make factoring out repetition much easier. – jonrsharpe Oct 07 '15 at 15:53

1 Answers1

3

Don't bother. If you need a variable, define it. It's going to happen one way or another.


You can use a defaultdict, and then just increment various keys on the dict. The keys will be initialized for you. This is preferable to creating "variable variables".

from collections import defaultdict
counts = defaultdict(int)
counts[1] += 1
counts[2] += 2

If you want to count something as you iterate over it, use enumerate.

for i, item in enumerate(data):
    print(i)

Both your counter examples could be easily derived from a single count this way. (They could also just be derived from the length of the data).

davidism
  • 121,510
  • 29
  • 395
  • 339