If list index exists, do X

前端 未结 12 910
清酒与你
清酒与你 2020-12-02 11:41

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

12条回答
  •  北荒
    北荒 (楼主)
    2020-12-02 12:18

    Oneliner:

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

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

提交回复
热议问题