If you read enough Python threads, you will see the same question appear whenever looping and indexing come up: what exactly does range do, how are its arguments interpreted, and when should you use it versus iterating directly over items?
Hi all, I am a bit confused about how to use the range() function in Python for loops. I want to understand: how start, stop, and step work, how to loop backward, how to iterate in fixed-size batches, when to use range with enumerate, and what common pitfalls to avoid. Examples would be great.
The range type in Python is a memory efficient, immutable sequence of integers commonly used in for loops. It doesn’t allocate a list of numbers; it generates values on demand, which makes it ideal for large loops.
- range(stop): starts at 0, increments by 1, ends before stop
- range(start, stop): starts at start, increments by 1, ends before stop
- range(start, stop, step): starts at start, increments by step, ends before reaching stop
# 0, 1, 2, 3, 4
for i in range(5):
print(i)
# 1, 2, 3, 4, 5
for i in range(1, 6):
print(i)
# 0, 2, 4, 6, 8
for i in range(0, 10, 2):
print(i)
# 10, 9, 8, 7, 6
for i in range(10, 5, -1):
print(i)Code language: PHP (php)
- Index-based iteration when you need positions:
items = ["a", "b", "c"]
for i in range(len(items)):
print(i, items[i])Code language: PHP (php)
- Prefer enumerate when you just need index and value:
for i, item in enumerate(items):
print(i, item)Code language: PHP (php)
- Fixed-size batching:
data = list(range(23))
batch_size = 5
for start in range(0, len(data), batch_size):
batch = data[start:start + batch_size]
print(batch)Code language: PHP (php)
- Loop a specific number of times without caring about the counter:
for _ in range(3):
print("retrying...")Code language: PHP (php)
- Reverse iteration:
for i in reversed(range(5)): # 4, 3, 2, 1, 0
print(i)Code language: PHP (php)
- Off-by-one errors: Remember that
stopis exclusive. If you want 1 to 10 inclusive, use range(1, 11). - Zero or misplaced step:
stepcannot be 0. Also, ensurestepmatches the direction of start to stop. - Unnecessary list conversion:
list(range(...))materializes the whole sequence. Only do it if you truly need a list.
- Memory friendly: range stores only start, stop, step, not all integers.
- Supports membership and length in O(1):
r = range(1, 1000000, 3)
print(len(r)) # fast
print(10 in r) # fast arithmetic checkCode language: PHP (php)
Iterating over files, frames, or image assets is a common use case. For example, you might export a sequence of thumbnails at fixed intervals or process a dataset in batches.
from pathlib import Path
from PIL import Image
src_dir = Path("input")
dst_dir = Path("output")
dst_dir.mkdir(exist_ok=True)
images = sorted(src_dir.glob("*.jpg"))
for i in range(0, len(images), 10): # process every 10th image
img_path = images[i]
with Image.open(img_path) as im:
thumb = im.resize((320, 320))
thumb.save(dst_dir / f"thumb_{i:04d}.jpg", quality=85)Code language: PHP (php)
When choosing formats inside such loops, review format tradeoffs like JPEG vs PNG to balance quality and size.
If you want to automate uploads and delivery at scale, you can pair range with a cloud media platform. For example, you can iterate deterministically over files, upload them programmatically, and output consistent public IDs for reliable downstream delivery. Cloudinary also offers a collection of handy online media tools if you need quick format conversions or basic edits before uploading.
# pip install cloudinary
import cloudinary
import cloudinary.uploader
from pathlib import Path
cloudinary.config(
cloud_name="YOUR_CLOUD_NAME",
api_key="YOUR_API_KEY",
api_secret="YOUR_API_SECRET"
)
src_dir = Path("output") # from previous step
imgs = sorted(src_dir.glob("thumb_*.jpg"))
for i in range(len(imgs)):
path = str(imgs[i])
public_id = f"project/thumb_{i:04d}"
cloudinary.uploader.upload(
path,
public_id=public_id,
overwrite=True,
folder="project"
)
# Later, deliver:
# https://res.cloudinary.com/YOUR_CLOUD_NAME/image/upload/w_320,c_fill/project/thumb_0000.jpgCode language: PHP (php)
For more Python-centric processing ideas that integrate nicely with remote delivery, the resources above on saving and analyzing images will help you structure robust loops and pipelines.
range(start, stop, step)yields integers up to but not including stop.- Use
enumeratefor index plus value, and range for batching or when you truly need indices. - Try not to convert
rangeto a list unless required; it is memory efficient by design. - Validate
stepand watch for off-by-one mistakes.
Ready to streamline how you process and deliver images and videos in Python-driven projects? Create your free Cloudinary account and start building efficient, scalable media workflows today.