user1569317 user1569317 - 1 year ago 121
Python Question

If list index exists, do X

In my program, user inputs number

, and then inputs
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

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 ()

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

if nams[3]: #etc.

Answer Source

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?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download