Or maybe I should say, ways to skip having to initialize at all.
I really hate that every time I want to do a simple count variable, I have to say, "hey python, this variable starts at 0." I want to be able to say count+=1
and have it instantly know to start from 0 at the first iteration of the loop. Maybe there's some sort of function I can design to accomodate this? count(1)
that adds 1 to a self-created internal count variable that sticks around between iterations of the loop.
I have the same dislike for editing strings/lists into a new string/list.
(Initializing new_string=""/new_list=[]
before the loop).
I think list comprehensions may work for some lists.
Does anyone have some pointers for how to solve this problem? I am fairly new, I've only been programming off and on for half a year.
Disclaimer: I do not think that this will make initialization any cleaner. Also, in case you have a typo in some uses of your counter variable, you will not get a
NameError
but instead it will just silently create and increment a second counter. Remember the Zen of Python:Having said that, you could create a special class that will automatically add missing attributes and use this class to create and auto-initialize all sorts of counters:
Now you can create a single instance of that class to create an arbitrary number of counters of the same type. Example usage:
In fact, this is similar to what
collections.defaultdict
does, except that you can use dot-notation for accessing the counters, i.e.c.foo
instead ofc['foo']
. Come to think of it, you could even extenddefaultdict
, making the whole thing much simpler: