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

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.
Asked By: user1569317



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

This is the perfect use for a try block:


except IndexError:
    print('sorry, no 5')   

# Note: this only is a valid test in this context 
# with absolute (ie, positive) index
# a relative index is only showing you that a value can be returned
# from that relative index from the end of the list...

However, by definition, all items in a Python list between 0 and len(the_list)-1 exist (i.e., there is no need for a try block if you know 0 <= index < len(the_list)).

You can use enumerate if you want the indexes between 0 and the last element:


for i, name in enumerate(names):
    print(i + ' ' + name)
    if i in (3,4):
        # do your thing with the index 'i' or value 'name' for each item...

If you are looking for some defined ‘index’ though, I think you are asking the wrong question. Perhaps you should consider using a mapping container (such as a dict) versus a sequence container (such as a list). You could rewrite your code like this:

def do_something(name):
    print('some thing 1 done with ' + name)
def do_something_else(name):
    print('something 2 done with ' + name)        
def default(name):
    print('nothing done with ' + name)     
    3: do_something,        
    4: do_something_else
n = input ("Define number of actors: ")
count = 0
names = []

for count in range(n):
    print("Define name for actor {}:".format(count+1))
    name = raw_input ()
for name in names:
    except KeyError:

Runs like this:

Define number of actors: 3
Define name for actor 1: bob
Define name for actor 2: tony
Define name for actor 3: alice
some thing 1 done with bob
something 2 done with tony
nothing done with alice

You can also use .get method rather than try/except for a shorter version:

>>> something_to_do.get(3, default)('bob')
some thing 1 done with bob
>>> something_to_do.get(22, default)('alice')
nothing done with alice
Answered By: dawg

len(nams) should be equal to n in your code. All indexes 0 <= i < n “exist”.

Answered By: jfs

If you want to iterate the inserted actors data:

for i in range(n):
    if len(nams[i]) > 3:
    if len(nams[i]) > 4:
Answered By: gepatino

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?

Answered By: JonathanV

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

You already know how to test for this and in fact are already performing such tests in your code.

The valid indices for a list of length n are 0 through n-1 inclusive.

Thus, a list has an index i if and only if the length of the list is at least i + 1.

Answered By: Karl Knechtel

ok, so I think it’s actually possible (for the sake of argument):

>>> your_list = [5,6,7]
>>> 2 in zip(*enumerate(your_list))[0]
>>> 3 in zip(*enumerate(your_list))[0]
Answered By: avloss

Do not let any space in front of your brackets.


n = input ()

You should add comments over and/or under your code. Not behind your code.

Have a nice day.

Answered By: Mr. Robot

Using the length of the list would be the fastest solution to check if an index exists:

def index_exists(ls, i):
    return (0 <= i < len(ls)) or (-len(ls) <= i < 0)

This also tests for negative indices, and most sequence types (Like ranges and strs) that have a length.

If you need to access the item at that index afterwards anyways, it is easier to ask forgiveness than permission, and it is also faster and more Pythonic. Use try: except:.

    item = ls[i]
    # Do something with item
except IndexError:
    # Do something without the item

This would be as opposed to:

if index_exists(ls, i):
    item = ls[i]
    # Do something with item
    # Do something without the item
Answered By: Artyer

You can try something like this

list = ["a", "b", "C", "d", "e", "f", "r"]

for i in range(0, len(list), 2):
    print list[i]
    if len(list) % 2 == 1 and  i == len(list)-1:
    print list[i+1];
Answered By: Suresh Kumar

It can be done simply using the following code:

if index < len(my_list):
    print(index, 'exists in the list')
    print(index, "doesn't exist in the list")
Answered By: user6039980


do_X() if len(your_list) > your_index else do_something_else()  

Full example:

In [10]: def do_X(): 
    ...:     print(1) 

In [11]: def do_something_else(): 
    ...:     print(2) 

In [12]: your_index = 2                                                                                                                                                                                                                       

In [13]: your_list = [1,2,3]                                                                                                                                                                                                                  

In [14]: do_X() if len(your_list) > your_index else do_something_else()                                                                                                                                                                      

Just for info. Imho, try ... except IndexError is better solution.

Answered By: Eduard Golubov

Here’s a simple, if computationally inefficient way that I felt like solving this problem today:

Just create a list of available indices in my_list with:

indices = [index for index, _val in enumerate(my_list)]

Then you can test before each block of code:

if 1 in indices:
    "do something"
if 2 in indices:
    "do something more"

but anyone reading this should really just take the correct answer from: @user6039980

Answered By: SurpriseDog
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.