so im trying to see if all the ints in a list are odd, or even, or both odd and even. I have a general framework down, but is it possible for me to address all the ints in a list at once, and see if they are odd or even?
Asked
Active
Viewed 270 times
-2
-
How can something be odd *and* even? – MattDMo Oct 08 '20 at 21:15
-
1Define "at once". – superb rain Oct 08 '20 at 21:15
-
2@MattDMo Schrödinger's number. – superb rain Oct 08 '20 at 21:16
-
@MattDMo xD I think they meant if the entire list is odd or even or has both odd or even in it – monsieuralfonse64 Oct 08 '20 at 21:16
-
@monsieuralfonse64 that makes sense... – MattDMo Oct 08 '20 at 21:17
-
Does this answer your question? https://stackoverflow.com/questions/10666163/how-to-check-if-all-elements-of-a-list-matches-a-condition – CrazyChucky Oct 08 '20 at 21:18
-
Actually OP, do you mean to check if the entirety of the list contains only even integers or only odd integer, or a mix of both? Or are you simply trying to loop through your list, checking if each integer is odd or even? – monsieuralfonse64 Oct 08 '20 at 21:18
-
@CrazyChucky thanks for the link! – Ides784 Oct 08 '20 at 21:24
3 Answers
3
Use all()
allEven = all(x % 2 == 0 for x in data)
allOdd = all(x % 2 != 0 for x in data)
Similarly, any()
for contains at least one odd or even
both odd and even
That's not possible.. ? Unless you mean within any given list, it contains a mix of both, in which case
oddAndEven = not (allOdd or allEven)

OneCricketeer
- 179,855
- 19
- 132
- 245
-
yeah sorry about the wording, i meant if all the ints are odd, even, or a mix of odds and evens – Ides784 Oct 08 '20 at 21:24
1
Try this:
all(i%2==0 for i in your_list)
for even. It will return True if all numbers are even. Similarly for odds:
all(i%2==1 for i in your_list)

IoaTzimas
- 10,538
- 2
- 13
- 30
0
li = [2, 4, 6]
#li = [1, 3]
#li = [1, 2, 3]
even = all(item % 2 == 0 for item in li)
odd = all(item % 2 == 1 for item in li)
mixed = not even and not odd
print('even', even)
print('odd', odd)
print('mixed', mixed)

Hocli
- 146
- 3