Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test if an index of a list exists

Tags:

python

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?

like image 657
user1427661 Avatar asked Sep 22 '12 04:09

user1427661


1 Answers

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:

from collections import defaultdict

# don't name a variable 'list'; you'll end up hiding the actual list type
my_List = defaultdict(int) # create a mapping, elements will default to 0

Then you can use

my_list[i] += 1

for any value of i. If it has been seen before, then it will increment it. If not, then my_list[i] will get a default value of 0, which will immediately be incremented to 1.

like image 180
Ian Clelland Avatar answered Nov 03 '22 20:11

Ian Clelland