Mastering List Manipulation

Lists become truly powerful when combined with methods and slicing operations. These techniques allow dynamic modification and extraction of list contents.

Essential List Methods

append(item)

fruits = ["apple", "banana"]
fruits.append("orange")
print(fruits) # → ["apple", "banana", "orange"]
["apple", "banana", "orange"]

pop()

last_fruit = fruits.pop()
print(f"Removed: {last_fruit}, Remaining: {fruits}")
Removed: orange, Remaining: ["apple", "banana"]

Slicing Syntax

numbers = [10, 20, 30, 40, 50]
middle = numbers[1:4] # → [20, 30, 40]
first_three = numbers[:3] # → [10, 20, 30]
[20, 30, 40]
[10, 20, 30]
Slice syntax: list[start:end]
  • Start index is inclusive
  • End index is exclusive
  • Omitted start/end defaults to 0/length

Common Errors

# Forgetting parentheses in pop()
items.pop # → Wrong! Needs ()
# Off-by-one slice errors
vals[1:2] # Gets only index 1

Practical Use: Playlist Manager

playlist = ["song1", "song2", "song3"]
playlist.append("song4")
current_song = playlist.pop(0)
next_up = playlist[:2]
print(f"Now playing: {current_song}, Next: {next_up}")
Now playing: song1, Next: ["song2", "song3"]

Your Task: To-Do List Manager

Given the initial list tasks = ["eat", "sleep", "code"]:

  1. Add "repeat" to end using append()
  2. Remove last item with pop() and store in popped
  3. Extract 2nd and 3rd items using slicing (indexes 1-2)

Final output should be: List: ['eat', 'sleep', 'code'], Popped: repeat, Slice: ['sleep', 'code']

Section 1/5Essential List Methods

Essential List Methods

append(item)

Mastering List Manipulation

Lists become truly powerful when combined with methods and slicing operations. These techniques allow dynamic modification and extraction of list contents.

Essential List Methods

append(item)

fruits = ["apple", "banana"]
fruits.append("orange")
print(fruits) # → ["apple", "banana", "orange"]
["apple", "banana", "orange"]

pop()

last_fruit = fruits.pop()
print(f"Removed: {last_fruit}, Remaining: {fruits}")
Removed: orange, Remaining: ["apple", "banana"]

Output:

Click "Check" to run your code.