Menu
CoddyTech

seq_along and range

Lesson 17 of 48 in Coddy's Python for R Developers course.

R for loops iterate values, as Python for loops do. Python range produces a reusable integer sequence with an excluded stop; R colon sequences include both endpoints and can descend. In R, one colon zero is a two-element descending sequence rather than an empty sequence, so seq_along is safer for indexes over a possibly empty vector. Python range(len(values)) is empty for an empty list, and direct iteration often avoids indexes entirely. Python loop targets bind element objects; incrementing an integer target does not replace the list slot. Use a comprehension when creating transformed values.

R

cat(1:0, "\n")
cat(length(seq_along(numeric(0))), "\n", sep="")

Python

values = [2, 4]
for value in values:
    value += 1
print(values)
print(list(range(0, 2)))

Porting trap

Do not translate R inclusive bounds without adjusting the Python stop. Prefer direct iteration when an index is unnecessary.

challenge icon

Challenge

Beginner

Read two integer lines, start then stop, each between -100 and 100. Print the sum of all integers from start through stop, inclusive. If start > stop, print 0. Print one integer and a newline. Keep the supplied input scaffold.

Your code goes in main.py. The locked driver.py starts your program and cannot be edited.

Try it yourself

# Starts the program in main.py. Edit main.py to solve the challenge.
from runpy import run_module

run_module("main", run_name="__main__")
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Python for R Developers

Practice on your own: Online Python compiler