If list index exists, do X

user1569317 picture user1569317 · Aug 2, 2012 · Viewed 295.2k times · Source

In my program, user inputs number n, and then inputs n number of strings, which get stored in a list.

I need to code such that if a certain list index exists, then run a function.

This is made more complicated by the fact that I have nested if statements about len(my_list).

Here's a simplified version of what I have now, which isn't working:

n = input ("Define number of actors: ")

count = 0

nams = []

while count < n:
    count = count + 1
    print "Define name for actor ", count, ":"
    name = raw_input ()
    nams.append(name)

if nams[2]: #I am trying to say 'if nams[2] exists, do something depending on len(nams)
    if len(nams) > 3:
        do_something
    if len(nams) > 4
        do_something_else

if nams[3]: #etc.

Answer

JonathanV picture JonathanV · Aug 2, 2012

Could it be more useful for you to use the length of the list len(n) to inform your decision rather than checking n[i] for each possible length?