Introduction
Imagine you have a row of boxes where you keep your toys. Sometimes you want to add a new toy, find a specific one, or remove one. Knowing how long these actions take helps you decide the best way to organize your toys.
Imagine a row of mailboxes where each mailbox holds a letter. You can open any mailbox directly to get the letter. To find a letter, you might check each mailbox one by one. Adding a letter at the end is easy, but adding one in the middle means shifting letters to make space. Removing a letter in the middle also requires shifting letters to close the gap.
┌───────────────┐ │ Array of Boxes│ ├─────┬─────┬─────┬─────┬─────┤ │ 0 │ 1 │ 2 │ 3 │ 4 │ ├─────┼─────┼─────┼─────┼─────┤ │ToyA │ToyB │ToyC │ToyD │ToyE │ └─────┴─────┴─────┴─────┴─────┘ Access: Direct jump to index 2 (ToyC) Search: Check boxes 0 to 4 until ToyD found Insert: Add ToyF at end (index 5) or shift toys to insert at index 2 Delete: Remove ToyB at index 1 and shift toys left
arr = [10, 20, 30, 40, 50] # Access element at index 2 print(arr[2]) # Output: 30 # Search for element 40 found = False for item in arr: if item == 40: found = True break print(found) # Output: True # Insert 25 at index 2 arr.insert(2, 25) print(arr) # Output: [10, 20, 25, 30, 40, 50] # Delete element at index 3 del arr[3] print(arr) # Output: [10, 20, 25, 40, 50]