Arrays and Lists
Arrays and Lists are fundamental data structures used to store collections of data. They allow you to hold multiple values under a single variable name, organized by an index.
1. Arrays vs. Lists
While often used interchangeably in conversation, there is a technical distinction in computer science:
- Arrays: Typically have a fixed size and store elements of the same data type. They are stored in contiguous memory locations. (Common in C, C++, Java).
- Lists (Dynamic Arrays): Can grow or shrink in size dynamically and often hold elements of mixed data types. (Common in Python, JavaScript, Ruby).
2. Declaration and Initialization
JavaScript (Array)
JavaScript arrays are dynamic and can hold mixed types.
let numbers = [1, 2, 3, 4, 5];
let mixed = ["Hello", 42, true];
Python (List)
Python lists are dynamic and very flexible.
numbers = [1, 2, 3, 4, 5]
fruits = ["apple", "banana", "cherry"]
Java (Array)
Java arrays are fixed-size and strongly typed.
// Size is fixed at initialization
int[] numbers = {1, 2, 3, 4, 5};
String[] names = new String[5]; // Empty array of size 5
3. Accessing Elements (Indexing)
Almost all modern programming languages use 0-based indexing, meaning the first element is at index 0.
let colors = ["Red", "Green", "Blue"];
console.log(colors[0]); // "Red"
console.log(colors[1]); // "Green"
4. Common Operations
Getting the Length
- JavaScript:
arr.length - Python:
len(arr) - Java:
arr.length
Adding Elements
- JavaScript:
arr.push("New Item") - Python:
arr.append("New Item") - Java: Cannot add to a standard array (must use
ArrayList).
Iterating (Looping)
# Python
for item in items:
print(item)