Question

Given the following if-statement:

if any(predicate(y) for y in range(0,len(myList))):

I am trying to keep the 'y' variable for follow-on actions, like so:

if any(predicate(y) for y in range(0,len(myList))):
    #DO STUFF WITH myList[y]

Unfortunately, this results in the following error:

NameError: global name 'y' is not defined

Short of trying to replicate the any() functionality with several nested loops, I cannot think of a way to persist the 'y' variable and am unable to find anything closely related on this site. Is this even possible?

Was it helpful?

Solution 2

How about you go about using slightly different logic if you want to persist the items:

 predRange = [x for x in range(0,len(myList)) if predicate(x)]
 if len(predRange) > 0:
   #hey look, it's already persisted in predRange!

OTHER TIPS

I'd write it this way:

for y, myItem in enumerate(myList):
    if predicate(y):
        #DO STUFF WITH myList[y]
        break
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top