Menu
CoddyTech

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 icon

Challenge

Beginner

Read 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__")
quiz iconTest yourself

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

All lessons in Python for JavaScript Developers

Practice on your own: Online Python compiler