Check if list index exists

Good, so these are actually two questions. First, I want to know if there is a way to check if the list index exists. For example, I want to increase the list [i] every time this condition is true, using a type code list[i] += 1, but if the index does not exist, I get an error. So I want to set up a test that, in case of an error, does something like list.append(1). What code can fulfill such a test condition? If list[i]gives an error message.

As a follow-up question, once the test is installed, is there a way to create a list index other than using the above add method?

+5
source share
4 answers

, , defaultdict - , - , .

( autovivificaiton perl, )

:

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

my_list[i] += 1

i. , . , my_list[i] 0, 1.

+8

, :

if 0 <= i < len(list): ... do something with list[i] ...
else: ... i is out of bounds, do something else ...

, , dict , , defaultdict.

+7

?

Range.

indexList = range(len(nameList))  # create a list of indexes
print "Index list:", indexList

for i in indexList:            # Pick items out of the list
    print ">>>", nameList[i] 

null python - ... ( , None , ).

if list[i] != None: #check if there is something there
    print "Oh hello... " + list[i]
else:
    print "Nothing to see here, move along"
+3

-, , , .

, ( 0) :

if i <= len(mylist):
   print mylist[i]

, IndexError, :

try:
  mylist[i] += 1
except IndexError:
  print "No item at ", i

, ?

, . , - .

, " " , , .

+1

All Articles