Lists Instead of Arrays
Lesson 12 of 48 in Coddy's Python for JavaScript Developers course.
Update an ordered collection and distinguish the changed list from a method result.
JavaScript
const colors = ["red", "blue"];
const result = colors.push("green");
console.log(result);
console.log(colors[colors.length - 1]);
console.log(colors.pop());Python
colors = ["red", "blue"]
result = colors.append("green")
print(result)
print(colors[-1])
print(colors.pop())What changes
The first line differs: JavaScript push returns the new length, 3; Python append returns None. Both examples then print green twice. A Python list stores ordered values and uses zero-based indexes. Negative indexes count from the end, so items[-1] accesses the last item. An invalid single index raises IndexError; it does not produce JavaScript's undefined. A slice such as items[1:3] creates a new outer list containing indexes one and two. The end index is excluded, and omitted bounds use the start or end. len(items) gives the number of elements. pop() removes and returns the last item; pop(0) removes and returns the first.
Common mistake
Do not write items = items.append(value). That replaces your list name with None. Mutation happens to the original list before the method returns.
Your task
Build a small list, update it, and report values after the update. Use the supplied four input lines without introducing an iteration loop.
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 JavaScript Developers
1From JavaScript to Python
Run Your First Python ProgramPrint, Comments, and StringsVariables Without let or constNumbers and ConversionBlocks Use IndentationRecap: Rewrite a Receipt4Iteration and Transformations
for Loops Iterate ValuesIndexes and Dict Iterationwhile, break, and continueComprehensions and SortingRecap: Build a Ranking2Values and Decisions
None, True, and FalseEquality and IdentityTruthiness and Short-CircuitBranches and ExpressionsRecap: Eligibility Rules3Collections and References
Lists Instead of ArraysTuples and UnpackingDictionaries and RecordsSets, Aliasing, and CopiesRecap: Clean an Inventory6Reliable Python Programs
Input and Output ContractsExceptions and ValidationModules and the Main GuardReading Type HintsRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler