Day 10, team—time to manipulate lists! Start with fruits = ["apple", "banana", "cherry"]—a string list. Print it first to see the original.
Create a list of fruits, then append a new one, remove one, sort the list, and print it before and after changes. (Concepts: .append(), .remove(), .sort())
Example Code:
fruits = ["apple", "banana", "cherry"]
print("Original:", fruits)
fruits.append("date")
fruits.remove("banana")
fruits.sort()
print("Modified:", fruits)Then, fruits.append("date") adds "date" to the end. Next, fruits.remove("banana") deletes the first occurrence of "banana"—it errors if not found, so ensure it exists. Finally, fruits.sort() rearranges the list alphabetically (or numerically for numbers)—it modifies the list in place, no new list created. Print again to see changes: Original: ['apple', 'banana', 'cherry'], Modified: ['apple', 'cherry', 'date'].
In your time, try .pop() to remove by index (e.g., fruits.pop(0) removes first) or .reverse() to flip order. Lists are dynamic—add/remove/sort makes them versatile for apps like inventories. Building on Day 8, you're editing data now!
Key Concepts:
- .append(): (Repeated from Day 8) Adds an item to the end of a list.
- .remove(): A list method that deletes the first occurrence of a specified value from the list.
- .sort(): A list method that sorts the list in ascending order (alphabetical for strings, numerical for numbers) and modifies it in place.
