Arrays and linked lists are both ways to store multiple items. Why can arrays get to an item faster than linked lists?
Think about how the computer finds the 5th item in an array versus a linked list.
Arrays keep items next to each other in memory. This lets the computer jump directly to any item using math. Linked lists store items scattered in memory, so the computer must follow links one by one.
Consider this Python code that uses a list to simulate an array. What is printed?
arr = [0] * 5 arr[0] = 10 arr[3] = 20 print(arr)
Remember, list indices start at 0.
We create a list of 5 zeros. Then we set index 0 to 10 and index 3 to 20. The rest stay 0.
Look at this code. Why does it cause an error?
arr = [1, 2, 3] print(arr[3])
Check the length of the list and valid index range.
The list has 3 elements at indices 0, 1, and 2. Index 3 is out of range, causing IndexError.
What does this code print?
arr = [1, 2, 3] arr.append(4) arr.pop(0) print(arr)
Remember what append and pop do to the list.
append(4) adds 4 at the end. pop(0) removes the first element (1). The list becomes [2, 3, 4].
Why do programmers use arrays instead of many separate variables like x1, x2, x3, ...?
Think about how you would handle 100 scores without arrays.
Using arrays, we can store many items with one name and use an index to access each. This avoids writing many variable names and makes loops possible.