Arrays vs Lists
Ordered collections and their manipulation
Introduction
In this lesson, you'll learn about arrays vs lists in Python. Coming from JavaScript, you already have a foundation for understanding this concept. We'll build on that knowledge while highlighting the key differences.
In JavaScript, you're familiar with ordered collections and their manipulation.
Python has its own approach to ordered collections and their manipulation, which we'll explore step by step.
The Python Way
Let's see how Python handles this concept. Here's a typical example:
fruits = ["apple", "banana", "cherry"]
# Add / remove
fruits.append("date") # add to end
fruits.insert(0, "avocado") # add at index
fruits.pop() # remove last
fruits.pop(0) # remove first
# Slice
sliced = fruits[1:3]
fruits[1:2] = ["blueberry"]
# Iteration
for f in fruits:
print(f)
upper = [f.upper() for f in fruits]
long = [f for f in fruits if len(f) > 5]
total = sum([1, 2, 3])Comparing to JavaScript
Here's how you might have written similar code in JavaScript:
const fruits = ["apple", "banana", "cherry"];
// Add / remove
fruits.push("date"); // add to end
fruits.unshift("avocado"); // add to front
fruits.pop(); // remove last
fruits.shift(); // remove first
// Slice & splice
const sliced = fruits.slice(1, 3);
fruits.splice(1, 1, "blueberry");
// Iteration
fruits.forEach(f => console.log(f));
const upper = fruits.map(f => f.toUpperCase());
const long = fruits.filter(f => f.length > 5);
const total = [1,2,3].reduce((acc, n) => acc + n, 0);You may be used to different syntax or behavior.
Python uses append() where JS uses push()
You may be used to different syntax or behavior.
Python slicing uses [start:end] syntax
You may be used to different syntax or behavior.
List comprehensions replace map/filter
You may be used to different syntax or behavior.
Python has built-in sum(), min(), max()
Step-by-Step Breakdown
1. Adding Elements
Python's append() adds to the end; insert(i, val) adds at a specific index.
arr.push("x"); // end
arr.unshift("x"); // frontlst.append("x") # end
lst.insert(0,"x") # front2. Slicing
Python slicing is built into the language with [start:end:step] syntax.
arr.slice(1, 3)lst[1:3]3. List Comprehensions
List comprehensions are the Pythonic way to replace map() and filter().
const upper = arr.map(x => x.toUpperCase());
const long = arr.filter(x => x.length > 5);upper = [x.upper() for x in lst]
long = [x for x in lst if len(x) > 5]Common Mistakes
When coming from JavaScript, developers often make these mistakes:
- Python uses append() where JS uses push()
- Python slicing uses [start:end] syntax
- List comprehensions replace map/filter
Key Takeaways
- append() ≈ push(), insert(0,x) ≈ unshift()
- lst[1:3] ≈ arr.slice(1,3)
- List comprehensions replace map/filter