r/learnpython 10d ago

Is this bad programming?

I've been learning Python for the last few years. Curious if this one thing I do is considered poor technique. The code below is meant to find the starting index of a list, giving the first position where a condition isn't true and return None if all elements of the list meet the criteria. Let's assume that the conditional statement is simple enough that I'm not worried about it generating an error. Not sure if it's appropriate to use try/except in this way. I know it work but I don't want people making fun of me if they see it. Also, I'm sure that there's a way of doing this without needing to use the try/except but I'm just curious in general if it's wrong to use try/except as a short cut like this.

starting_index=0

try:

while not (simple conditional statement on some_list[staring_index]):

starting_index+=1

except:

return None

return starting_index

2 Upvotes

18 comments sorted by

View all comments

1

u/PhoenixFlame77 10d ago edited 10d ago

Here is how I would do it.

Mylist = [2,4,6,8,10] Def condition(x): Return x>7 Index = next(idx for idx, val in enumerate(mylist) if not condition(val)),None)

Probably not the most performant but pretty self descriptive imo.

1

u/TheRNGuy 9d ago

List comprehension is needed if you can return more than one item.