[go: up one dir, main page]

0% found this document useful (0 votes)
13 views2 pages

Python Range Cheat Sheet

Uploaded by

Akhilesh Saini
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views2 pages

Python Range Cheat Sheet

Uploaded by

Akhilesh Saini
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Python range() Cheat Sheet

Basic Syntax

range(stop)

range(start, stop)

range(start, stop, step)

How It Works

- start: starting number (default = 0)

- stop: stopping number (exclusive)

- step: increment (default = 1)

Examples

range(5) -> 0, 1, 2, 3, 4

range(2, 6) -> 2, 3, 4, 5

range(1, 10, 2) -> 1, 3, 5, 7, 9

range(10, 0, -2) -> 10, 8, 6, 4, 2

Common Use Cases

Looping:

for i in range(5): print(i)

Index Looping:

for i in range(len(items)): print(i, items[i])

Better:

for i, item in enumerate(items): print(i, item)

Caveats & Gotchas

- stop is exclusive: range(5) gives 0 to 4, not 5

- step cannot be zero: raises ValueError

- range() returns a lazy object (not a list)


Python range() Cheat Sheet

Pros

- Memory-efficient (no list stored in memory)

- Fast iteration

- Flexible (negative steps, large ranges)

- Supports slicing like lists

Cons

- Not a list (can't use .append())

- Needs list() to view/modify

- Immutable

Best Practices

- Use range() over while when counting

- Avoid range(len(...)) when possible

- Use enumerate for index loops

- Use range(..., -1, -1) for reverse loops

Advanced Features

- Slicing: list(range(10)[2:7]) -> [2, 3, 4, 5, 6]

- Convert: list(range(3)), tuple(range(3))

Summary Table

range(5) -> 0 to 4

range(2, 6) -> 2 to 5

range(1, 10, 2) -> 1, 3, 5, 7, 9

range(10, 0, -2) -> 10, 8, 6, 4, 2

list(range(3)) -> [0, 1, 2]

enumerate(mylist) -> Use instead of range(len(...))

You might also like