print (or execute statements) inside python list comprehension

list-comprehension, python

Solution

Whoops, so I realized the answer to this after posting it! >:O

I just need to make another function:

def h(i,list_of_numbers):
    try: g(list_of_numbers[i])
    except: 
        print (i,list_of_numbers[i]))
        raise Exception("Danger Will Robinson!")
return i

Then I can just make my list comprehension:

[h(i) for i in range(n) if g(list_of_numbers[i]) > 0]

...and I guess that technique should work for executing any statement I want. Darn, I was so excited to finally have something to post on stack exchange!

Problem

I'm wondering if there is any way to print (or, more generally, execute statements) inside a list comprehension. So we're all on the same page, consider the list comprehension inside the following function, f: ``` def g(x): return some_complicated_condition_function(x) def f(list_of_numbers,n): return [i for i in range(n) if g(list_of_numbers[i]) > 0] ``` Say I get some mysterious error when calling f and want to debug by catching the error using something like: ``` try: g(list_of_numbers[i]) except: print (i,list_of_numbers[i])) raise Exception("Danger Will Robinson!") ``` Is there anyway to do this without rewriting my list comprehension as a traditional for/while loop? Thanks! P.S. Maybe this is a horrible way to debug (I'm math, not CS), so if you have any tips don't be shy.

Original source