Lists and Arrays, Ordered Sequences

So far each variable has held a single value. But programs work with many things: every student in a class, every book on a shelf, every transaction in a day.

A Python list and a JavaScript array are the same idea: an ordered sequence of values in one container. They're a direct equivalent, one of the cleanest translations between the two languages.

Creating a sequence

PYTHON

cities = ["Accra", "Atlanta", "Kingston"]

JAVASCRIPT

let cities = ["Accra", "Atlanta", "Kingston"]; 
Compare → Square brackets, comma-separated values: identical syntax. Python calls it a list; JavaScript calls it an array. The name differs; the concept and the notation do not.
EXAMPLE
loading editor…
YOUR TURN
Your turn → Index 0 is the first item, always. Add a fourth city and print it by its index.
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.

✦ Zero-indexing, one more time

Position 0 is first, position 1 is second. A list of 3 items has valid indexes 0, 1, and 2. Asking for index 3 is asking for a fourth item that doesn't exist, Python raises an IndexError, JavaScript quietly returns undefined.

Mark this lesson complete

Signed in, your progress follows you to every device.

Next: Adding, Removing, Updating, Slicing →
← Back