Okay, so this is actually two questions. First, I want to know if there is a way to test if an index of a list exists. For example, I want to increment list[i] each time a given condition is true using code like list[i] += 1, but if the index doesn’t exists, I’m given an error. So I want to set up a test that, in the case of an error, does something like list.append(1). What code could accomplish such a testing condition? If list[i] throws an error.
As a follow up question, once the test is established, is there any way to create a list index aside from using the aforementioned append method?
It sounds like what you really want is a
defaultdict— not a list so much as a mapping of integers to some sort of count of the number of times you’ve seen them.(this is really close to the concept of autovivificaiton in perl, if you’ve used that before)
This code would work:
Then you can use
for any value of
i. If it has been seen before, then it will increment it. If not, thenmy_list[i]will get a default value of 0, which will immediately be incremented to 1.