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]
x at index 2 in an array arr in Python?insert(index, value) to add elements at a specific position.add and push are not valid list methods; append adds only at the end.arr = [10, 20, 30, 40, 50] arr.pop(1) print(arr)
pop(1) removes the element at index 1, which is 20.arr = [1, 2, 3, 4] arr.insert(5, 10) print(arr)
insert places the element at the end if index is greater than list length.Pass the test and this pattern moves unknown