Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If list index exists, do X

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. 
like image 827
user1569317 Avatar asked Aug 02 '12 21:08

user1569317


People also ask

How do you check if an index exists in a list?

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.

How do you check if a value is in a list Python?

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.

What does index function do in list?

The index() method returns the position at the first occurrence of the specified value.

What is list index out of range in Python?

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.


1 Answers

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?

like image 187
JonathanV Avatar answered Nov 13 '22 22:11

JonathanV