Skip to content

Support negative step in xfrange to match frange - #442

Closed
uttam12331 wants to merge 1 commit into
mahmoud:masterfrom
uttam12331:fix-xfrange-negative-step
Closed

Support negative step in xfrange to match frange#442
uttam12331 wants to merge 1 commit into
mahmoud:masterfrom
uttam12331:fix-xfrange-negative-step

Conversation

@uttam12331

Copy link
Copy Markdown
Contributor

Summary

xfrange is documented as "Same as frange, but generator-based" and shares frange's exact argument handling (including the range()-style start/stop swap). But its loop hard-codes the ascending condition:

cur = start
while cur < stop:
    yield cur
    cur += step

so a negative step yields nothing. frange supports a negative step — its docstring pins it:

>>> frange(5, 0, step=-1.25)
[5.0, 3.75, 2.5, 1.25]

whereas the equivalent xfrange call returned an empty generator:

>>> tuple(xfrange(5, 0, step=-1.25))
()          # before this fix; should equal frange's output

Fix

Choose the loop condition based on the sign of step:

-    while cur < stop:
+    while (cur < stop) if step > 0 else (cur > stop):

Tests

Added a negative-step doctest to xfrange mirroring frange's:

>>> tuple(xfrange(5, 0, step=-1.25))
(5.0, 3.75, 2.5, 1.25)

The existing positive-step doctest (xfrange(1, 3, step=0.75)) is unchanged and still passes. I verified xfrange now matches frange across all of frange's documented cases (ascending, empty, and the negative-step case).

xfrange is documented as "Same as frange" and shares its argument handling,
but its loop hard-coded the ascending condition `while cur < stop`, so a
negative step yielded nothing. frange handles a negative step (its docstring
pins `frange(5, 0, step=-1.25) == [5.0, 3.75, 2.5, 1.25]`), so `xfrange` with
the same arguments silently returned an empty generator instead.

Pick the loop condition based on the sign of step, and add a matching
negative-step doctest.
@mahmoud

mahmoud commented Aug 7, 2026

Copy link
Copy Markdown
Owner

Good catch, appreciate the effort. #443 reworked xfrange more broadly. Keep up the good work!

@mahmoud mahmoud closed this Aug 7, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants