Progress indicator from long running list comprehension

TrustyTony 1 Tallied Votes 1K Views Share

Sometimes, before optimizing your code, you may end up to have very slow running code in list comprehension statement. Because you have not yet tested the code fully, it easy to loose patience and just interrupt the code.

If you are making function, you can insert print statements for verification. But how to put print in list comprehension. If you are using function to produce the result you can insert a print there or you could use some debugging tools. I however often keep it simple and I came up with this pass through trivial function which basically just prints it's arguments and passes them through as result. You can insert this function for part which expects a sequence to iterate or produces a sublist or tuple.

Gribouillis commented: nice +13
def echo(*args):

n = 1000000
limit = int((n**2/2)**0.5) +1
result = [echo(x,(n**2 - x**2)**0.5) for x in range(int(n**0.5)-1,limit) if ((n**2 - x**2)**0.5).is_integer()]
Gribouillis 1,391 Programming Explorer Team Colleague

It is nice, but I think echo() should take a single argument and return a single argument like this

def echo(arg):
    return arg

Having a unary function allows use with imap() for example

from itertools import imap
s = sum(imap(echo, (x * x for x in range(5))))
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.