If list index exists, do X

前端 未结 12 792
清酒与你
清酒与你 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:19

    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?

    0 讨论(0)
  • 2020-12-02 12:20

    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:
            break
        print list[i+1];
    
    0 讨论(0)
  • 2020-12-02 12:22

    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.

    0 讨论(0)
  • 2020-12-02 12:25

    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:.

    try:
        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
    else:
        # Do something without the item
    
    0 讨论(0)
  • 2020-12-02 12:30

    It can be done simply using the following code:

    if index < len(my_list):
        print(index, 'exists in the list')
    else:
        print(index, "doesn't exist in the list")
    
    0 讨论(0)
  • 2020-12-02 12:30

    A lot of answers, not the simple one.

    To check if a index 'id' exists at dictionary dict:

    dic = {}
    dic['name'] = "joao"
    dic['age']  = "39"
    
    if 'age' in dic
    

    returns true if 'age' exists.

    0 讨论(0)
提交回复
热议问题