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

后端 未结 8 1944
离开以前
离开以前 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:01

    Even numbers are divisible by 2. Odd numbers are not.

    len(X) will get the length of X

    If the length of X is divisible by 2, then it is an Even number If the length of X is not divisible by 2 then it is an Odd Number

    len(X)%2 returns the "remainder" of a division problem

    for example 5%2 will return 1 which is NOT zero, (because 5 divided by 2 is 2 with a remainder of 1), therefore it is not even. Same thing as 6%4 which would return a 2, because 6 divided by 4 is 1 with a remainder of 2.

    so len(X)%2 where X is your list, will return either a 1, indicating it is Odd, or a 0 indicating it is Even.

提交回复
热议问题