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
BeginnerRead 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__")
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Python for R Developers
1From R to Python
Run Your First Python Programcat, print, and StringsBindings and Copy SemanticsInteger Arithmetic and NABraces Become SuitesRecap: Rewrite a Receipt4Iteration and Transformations
seq_along and rangeitems and enumeratenext and continuelapply and ComprehensionsRecap: Build a Ranking2Values and Decisions
NULL, NA, and NoneVector Equality and IdentityScalar Conditions, Not Vectorsifelse and Scalar SelectionRecap: Eligibility Rules3Vectors to Containers
Vectors, Lists, and Index ZeroTuples and Exact UnpackingNamed Lists and Dictionariesunique and Shallow CopiesRecap: Clean an Inventory6Reliable Python Programs
readLines and Text ContractsConditions and Cleanupsource and Module ImportsAnnotations and Runtime TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler