TIMEX
TIMEX

Reputation: 271874

Is there an easy way to write this in Python?

        if(i-words < 0):
            start_point = 0
        else:
            start_point = i - words

Or is this the easiest way using min/max? This is for lists splicing.

I want start_point to always be 0 or above.

Upvotes: 2

Views: 207

Answers (2)

Delan Azabani
Delan Azabani

Reputation: 81394

How about

start_point = 0 if i - words < 0 else i - words

or

start_point = i - words if i - words < 0 else 0

or even better, the clearest way:

start_point = max(i - words, 0)

As Mihai says in his comment, the last way is not only clearer to read and write, but evaluates the value only once, which could be important if it's a function call.

Upvotes: 1

Mihai Maruseac
Mihai Maruseac

Reputation: 21435

Better is to make the limiting more obvious

start_point = max(i - words, 0)

This way, anyone reading can see that you're limiting a value.

Using any form of if has the disadvantage that you compute twice i - words. Using a temporary for this will make more code bloat.

So, use max and min in these cases.

Upvotes: 10

Related Questions