Borrowed Iteration to for
Lesson 17 of 48 in Coddy's Python for Rust Developers course.
Rust chooses ownership behavior through iter, iter_mut, and into_iter. Python for value in values binds the loop name to each element object and does not consume the list or create an exclusive borrow. Rebinding an integer loop name does not replace a slot; mutating a contained list does mutate that shared element. Python range(3) yields zero, one, and two, like Rust 0..3. Use indexed assignment or a comprehension to replace integer elements.
Rust excerpt inside main
let values = vec![2, 4];
for value in &values { println!("{}", value); }
for i in 0..3 { println!("{}", i); }Python
for value in [2, 4]:
print(value)
for i in range(3):
print(i)Porting trap
A Python loop does not prevent you from structurally mutating its list while iterating, but doing so can skip elements. Build a filtered copy when removing items.
Implement the specified API in the editable Python files. The locked driver.py runs the program and supplies input/output. Keep its imports and names unchanged.
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 Rust Developers
1From Rust to Python
Run Your First Python ProgramMacros to printBindings, mut, and ShadowingIntegers and Floor DivisionIndentation and ScopeRecap: Rewrite a Receipt4Iteration and Transformations
Borrowed Iteration to forEntries and enumeratewhile, break, and continueIterators and ComprehensionsRecap: Build a Ranking2Values and Decisions
Option and NoneEquality and Object IdentityTruth Tests and FallbacksIf Expressions and elifRecap: Eligibility Rules3Ownership and Collections
Vec to listTuples and DestructuringHashMap to dictClone and Shallow CopiesRecap: Clean an Inventory6Errors and Modules
Text Input and FormattingResult, Exceptions, and withModules and the Main GuardHints Without Borrow CheckingRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler