How to know if a list has an even or odd number of elements

后端 未结 8 1928
离开以前
离开以前 2021-01-28 01:20

How can I find out if there is even, or odd, number of elements in an arbitrary list.

I tried list.index() to get all of the indices... but I still don\'t k

相关标签:
8条回答
  • 2021-01-28 02:17
    if len(mylist)%2==0:
         #even
    else:
         #odd
    
    0 讨论(0)
  • 2021-01-28 02:17

    Using the modulus operator - % gives the remainder. To get if even, you need to divide by 2, for example:

    7 % 2 = 1
    8 % 2 = 0
    

    The most pythonic way to do it is:

    def is_even(your_list):
        if not len(your_list) % 2:  # 0 in case of even i.e. No remainder
            return True
        else:
            return False
    
    0 讨论(0)
提交回复
热议问题