Courses / Data Structures and Algorithms
1. Arrays
Understanding the array data structure and its properties.
How It Works
Think of an array like a row of mailboxes, where each mailbox can hold a letter (value) and can be accessed by its position (index).
Arrays store elements in a fixed-size, contiguous block of memory.
Each element can be accessed using its index, starting from zero.
Arrays allow for efficient iteration and manipulation of data.
Arrays can be resized or modified, but this may involve creating a new array.
See It
The code creates an array with five elements and prints the third element (index 2), which is 3. You could try changing the index to see different outputs.
arr = [1, 2, 3, 4, 5]
print(arr[2]) # Accessing the third elementUse It
Arrays are used to store lists of items, such as scores in a game.
scores = [88, 92, 76, 81]
average_score = sum(scores) / len(scores)
print(average_score)Using an array to store scores allows for easy calculations and data manipulation.
Break It
What will this print?
arr = [10, 20, 30, 40]
print(arr[4]) # Trying to access an out-of-bounds indexThis error occurs because the code tries to access an index that does not exist in the array, which only has indices 0 to 3.
To fix this, ensure that you access an index that exists within the bounds of the array.
arr = [10, 20, 30, 40]
print(arr[3]) # Accessing the last element correctlyLevel Up
Multidimensional Arrays: These are arrays of arrays, allowing for the representation of more complex data structures like matrices.
Array Slicing: This technique allows you to access a subset of an array, making it easy to manipulate portions of data.
Prove It
Create an array of five integers and return the second element.
Python
Arrays
An array is a data structure that holds a collection of items, usually of the same type.
"I need a way to store multiple values in a single variable."
An array is a collection of items stored at contiguous memory locations, allowing for efficient access and manipulation of data.
"I need a way to store multiple values in a single variable."
An array is a collection of items stored at contiguous memory locations, allowing for efficient access and manipulation of data.