jump to navigation

Slicing Numbers? March 7, 2012

Posted by PythonGuy in ideas.
add a comment

I can’t count the number of times I’ve written code like this:

remainder = ...
for item in items:
    item.amount = min(amount_wanted, remainder)
    remainder -= item.amount

There is something similar we do with list-like objects:

head, rest = stuff[:5], stuff[5:]

Which is, of course, absolutely beautiful. There is no reason why any language should not support the above syntax.

Isn’t the first code block above simply understood to mean the same thing? So why not:

amount, remainder = remainder[:amount_wanted], remainder[amount_wanted:]

This would behave, of course, exactly like the list indices. If the amount_wanted exceeds the amount, then simply return amount and 0, respectively.

Advertisements