r/PythonLearning • • 7h ago

Python library idea

Python learners and programmers: What's your biggest coding difficulty?

When using Python, what small problem or task do you find difficult or annoying?

Is there any function or simple tool you wish Python had to make coding easier?

I'm planning to build a small Python library based on real problems people face. I'd love to hear your experiences!

6 Upvotes

11 comments sorted by

View all comments

1

u/Fun_Army2398 7h ago

I'm not sure what to call it. Maybe "toggle based conditionals". Often I find myself writing some loop where, if a condition is met, a thing should happen, but only the first time that condition is met. It's really not that hard to solve with a boolean, but it'd be nice to have it all in one line.

Heres an example:

found:bool=False
data:list[int]=[0, 1, 2, 3, 4]
trigger:int=2
for i in data:
    if i > trigger and not found:
        doSomething()
        found=True
    else:
        soSomethingElse()

If this bothered me enough to fix, it might look something like:

def toggleBasedConditional(
    loop:iterable,
    trigger:callable[...,bool],
    triggered:callable[...,None],
    otherwise:callable[...,None]
) -> bool:
    pass
```

1

u/recentAd1666 6h ago

Depdendiing of your ultimate goal... You should try using

map(function, iterable)

or

While True: If condition: Break

1

u/Fun_Army2398 5h ago

I'm not sure how map would solve this. It would apply the same function to every element, so each time the trigger condition is met doSomething() would run, rather than only the first time. I'd still need to track that boolean manually. Right?

if trigger: break doesn't work because I want to keep processing the iterable after the trigger is found. If you meant if trigger: doSomething(); continue this doesn't work because I only want to doSomething() the first time trigger returns true.

The only way that I know of doing this is to track if that condition has been met yet or not.

1

u/recentAd1666 4h ago

If i understand well, you want to iterate a list, then when first trigger you doSomething (only once for the whole process), then for other number just doSomethingElse ?

1

u/Fun_Army2398 4h ago

Yes. Treat every element of the list the same, except for the first time some condition is met.

1

u/sexiestsaxiestman 52m ago

You might want to check out the built in itertools library