Adding, Removing, Updating, Slicing

Unlike strings, lists and arrays are mutable. You can change them in place. The four operations you'll use constantly: add to the end, remove, update by position, and slice out a section.

Adding and removing

PYTHON

cities.append("Lagos")   # add to end
cities.pop()            # remove last
cities.remove("Accra")  # remove by value

JAVASCRIPT

cities.push("Lagos");    // add to end
cities.pop();            // remove last
cities.splice(0, 1);     // remove by position
Compare → Same operations, different method names. Python appends; JavaScript pushes. Both pop. Removing by value is a one-liner in Python; JavaScript works by position with splice. Different syntax for a shared concept.
EXAMPLE
loading editor…
YOUR TURN
Your turn → Updating by index replaces that slot. Add a fourth artist you admire, then remove the second one.
loading editor…

Syntax has to be exact. Every quote, bracket and parenthesis needs its partner, and in Python the spaces at the start of a line count. One slip and the program won't run; the message will say where.

Slicing cuts a section out of a sequence: exactly like slicing a string, because both are sequences. Start included, end excluded.

EXAMPLE
loading editor…
YOUR TURN
Your turn → Python can leave either side of the colon blank to mean 'from the start' or 'to the end'. Add a line that prints only the last two numbers, and one that prints everything except the first.
loading editor…

Syntax has to be exact. Every quote, bracket and parenthesis needs its partner, and in Python the spaces at the start of a line count. One slip and the program won't run; the message will say where.

Mark this lesson complete

Signed in, your progress follows you to every device.

Next: Dictionaries and Objects, Labeled Data →
← Back