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.
To check if a list index exists in a list using Python, the easiest way is to use the Python len() function. You can also check if an index exists using exception handling.
We can use the in-built python List method, count(), to check if the passed element exists in the List. If the passed element exists in the List, the count() method will show the number of times it occurs in the entire list. If it is a non-zero positive number, it means an element exists in the List.
The index() method returns the position at the first occurrence of the specified value.
You'll get the Indexerror: list index out of range error when you try and access an item using a value that is out of the index range of the list and does not exist. This is quite common when you try to access the last item of a list, or the first one if you're using negative indexing.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With