Array Methods and Lists
Lesson 12 of 48 in Coddy's Python for Ruby Developers course.
A Python list is the usual counterpart of a Ruby array: it is ordered, mutable, growable, and stores object references. Both support negative indexes. Python slicing excludes the stop index, corresponding to the intent of a Ruby exclusive range slice. Indexing beyond a Ruby array commonly returns nil; Python indexing raises IndexError. Python slices clip oversized bounds. Ruby push and << return the modified array, which supports chaining. Python append mutates the list but returns None. The challenge also uses pop(0) to remove and return the first item, analogous to Ruby shift.
Ruby
items = [4, 8]
saved = items.push(12)
p savedPython
items = [4, 8]
saved = items.append(12)
print(saved)
print(items[-1])Porting trap
Do not assign the result of Python append back to your list. You would replace the list reference with None.
Challenge
BeginnerRead four integers on four lines. Create a list from the first three, append the fourth, then remove the first item with pop(0). Print the removed integer, the resulting last item, and the first two items of the resulting list on separate lines. Print the last line in Python list format, such as [2, 3]. Values range from -20 to 20.
Print only the requested output, with a newline after each line. Keep the supplied input scaffold. No loops or functions are needed.
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 Ruby Developers
1From Ruby to Python
Run Your First Python ProgramStrings and InterpolationNames and Mutable StringsDivision and ParsingFrom end to IndentationRecap: Rewrite a Receipt4Iteration and Transformations
each and Python foreach_pair and enumeratenext Becomes continueselect, map, and sort_byRecap: Build a Ranking2Values and Decisions
nil Becomes None== and equal?Zero Is False in Pythonelsif and Conditional ValuesRecap: Eligibility Rules3Collections and References
Array Methods and ListsParallel Assignment and TuplesHash Defaults and Dict Keysdup, Copies, and SetsRecap: Clean an Inventory6Reliable Python Programs
gets, input, and Formattingrescue and Context Managersrequire and Import GuardsHints Do Not Enforce TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler