0

Print number if each and every element of number is even:

a=[111,222,333,444,232,343]
count =0
b = []
for i in a:
    for j in str(i):
        if int(j) % 2 == 0:
            count +=1
            if count == len(str(i)):
                b.append(i)
        else:
            count = 0
            break
print b
YetAnotherBot
  • 1,937
  • 2
  • 25
  • 32
  • See [this](https://stackoverflow.com/questions/42730418/how-do-i-write-the-list-comprehension-for-the-given-code) – itsmysterybox Oct 31 '18 at 04:02
  • Possible duplicate of [if/else in Python's list comprehension?](https://stackoverflow.com/questions/4260280/if-else-in-pythons-list-comprehension) – Clock Slave Oct 31 '18 at 06:11

2 Answers2

2

This list comprehension works:

b = [i for i in a if all(int(j)%2 == 0 for j in set(str(i)))]

>>> b
[222, 444]

It includes casting to set, so that you only look at the unique characters making up each element. Also, it uses all to check that each character in that set is even.

sacuL
  • 49,704
  • 8
  • 81
  • 106
0

You can also use filter:

b = list(filter(lambda x: all(int(i)%2 == 0 for i in set(str(x))), a))
Levi
  • 21
  • 6