Sidharth Ghoshal
Sidharth Ghoshal

Reputation: 720

Is there a more pythonic way to evaluate "for some"?

Consider the pseudocode

if P(S) for some S in Iterator:
    Do something 

When I write this in python I usually end up writing something like

for S in Iterator:
    if P(S):
        Do something
        break 

Or if I want to avoid nesting an if in a loop

i = 0
while i < len(S) and not P(S[i]):
    i+=1
if i < len(S):
    Do something

Both of these are irritating to use. The code is direct yet my intent in pseudocode feels somewhat obfuscated. I might instead try to write

if [P(S) for S in Iterator if P(s)]:
    Do something

but that list comprehension will enumerate the entire iterator (I believe) and the P(S) is mentioned twice, and overloading the if statement with the list feels ugly.

Is there a better/more pythonic way to write that pseudocode in python?

Upvotes: 1

Views: 30

Answers (0)

Related Questions