Why This Matters
A single variable holds one value. But real programs work with collections — a list of users, a set of search results, a sequence of transactions. An array (called a list in Python) is the most fundamental collection: an ordered sequence of values, each accessible by its position.
Arrays are the data structure you'll use the most. Knowing how to create, access, transform, and iterate over arrays is essential for every programming task.
Define Terms
Visual Model
The full process at a glance. Click Start tour to walk through each step.
Arrays store ordered data accessible by numeric index, starting at 0.
Code Example
// Creating arrays
const fruits = ["apple", "banana", "cherry"];
const numbers = [10, 20, 30, 40, 50];
// Accessing elements (0-indexed)
console.log(fruits[0]); // "apple"
console.log(fruits[2]); // "cherry"
console.log(fruits.length); // 3
// Modifying arrays
fruits.push("date"); // add to end
fruits[1] = "blueberry"; // replace at index
console.log(fruits); // ["apple","blueberry","cherry","date"]
// MAP: transform every element
const doubled = numbers.map(n => n * 2);
console.log(doubled); // [20, 40, 60, 80, 100]
// FILTER: keep elements that pass a test
const big = numbers.filter(n => n > 25);
console.log(big); // [30, 40, 50]
// REDUCE: combine all elements into one value
const sum = numbers.reduce((acc, n) => acc + n, 0);
console.log(sum); // 150
// CHAINING: combine operations
const result = numbers
.filter(n => n > 15)
.map(n => n * 2);
console.log(result); // [40, 60, 80, 100]Interactive Experiment
Try these exercises:
- Create an array of 5 names. Print the first and last elements.
- Use
mapto convert an array of prices to prices with 10% tax added. - Use
filterto get only even numbers from[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]. - Use
reduceto find the largest number in an array. - What happens when you access an index that doesn't exist? (Try
arr[100].)
Quick Quiz
Coding Challenge
Write a function called `getPassingStudents` that takes an array of objects like `{name: 'Alice', score: 85}` and returns an array of names (strings) of students who scored 70 or above, sorted alphabetically.
Real-World Usage
Arrays are the most-used data structure in production software:
- API responses: Most REST APIs return lists of items:
[{id: 1, ...}, {id: 2, ...}] - React rendering:
items.map(item => <Component key={item.id} />)renders lists - Data pipelines: ETL processes chain filter → map → reduce over datasets
- Database results: SQL queries return arrays of row objects
- Event queues: Task schedulers process arrays of pending jobs