Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python list comprehension (if, continue, break)

I'm trying to make it a habit of creating list comprehensions, and basicly optimize any code I write. I did this little exercise to find if all digits in a given number is even, when trying to create a list with for loops and if statements i ran into a problem with "continue" & "break". Can i even insert those flow controls into a list?

I'd love to know how much i can shorten any piece of code. Here's what i wrote, i'd love to get feedback from you guys.

numbers = [str(x) for x in range(0, 10000)]

def is_all_even(nums):
    temp_lst = []
    evens_lst = []
    for x in nums:
        for y in x:
            if int(y) % 2 == 0:
                temp_lst.append(str(y))
                continue
            else:
                break
        if len(''.join(temp_lst[:])) == len(x):
            evens_lst.append(''.join(temp_lst[:]))
        del temp_lst[:]
    print(evens_lst)
like image 797
Alex Zel Avatar asked Apr 20 '15 19:04

Alex Zel


3 Answers

You can use a list comp,using all to find the numbers that contain all even digits:

print([s for s in numbers if all(not int(ch) % 2 for ch in s)])

all will short circuit on finding any odd digit.

If you don't want to store all the numbers in memory at once you can use a generator expression:

evens = (s for s in numbers if all(not int(ch) % 2 for ch in s))

To access the numbers you just need to iterate over evens:

for n in evens:
    print(n)

You could also use filter for a functional approach which returns an iterator in python 3:

In [5]: evens = filter(lambda x: all(not int(ch) % 2 for ch in x), numbers)

In [6]: next(evens)
Out[6]: '0'

In [7]: next(evens)
Out[7]: '2'

In [8]: next(evens)
Out[8]: '4'

In [9]: next(evens)
Out[9]: '6'
like image 158
Padraic Cunningham Avatar answered Sep 20 '22 16:09

Padraic Cunningham


[x for x in range(10000) if all(c in '02468' for c in str(x))]
like image 37
TigerhawkT3 Avatar answered Sep 16 '22 16:09

TigerhawkT3


Rather than sending the whole list of numbers to the function, you can send just one number to a function and then use the list comprehension to apply it to your list.

def is_all_even(num):
    return all(ch in '02468' for ch in str(num))

print([n for n in range(10000) if is_all_even(n)])
like image 31
Stuart Avatar answered Sep 18 '22 16:09

Stuart