Lists are not just storage. They come with built-in actions (methods) that let you add, remove, and modify elements.
🎯 What Are Methods?
A method is an action that an object can perform.
Syntax:
object.method()
For example:
my_list.append(5) # Call the append method on my_list
➕ append() — Add to the End
The most common method! Adds an element to the END of the list:
hand = ["🐲 Dragon", "🧙 Mage"]
print(hand) # ['🐲 Dragon', '🧙 Mage']
hand.append("⚔️ Knight")
print(hand) # ['🐲 Dragon', '🧙 Mage', '⚔️ Knight']
Where to use it:
- Dealing cards into a hand
- Adding a new player
- Collecting scores
Example: Dealing cards
import random
creatures = [
{"name": "🐲 Dragon", "attack": 8},
{"name": "🧙 Mage", "attack": 6},
{"name": "⚔️ Knight", "attack": 5}
]
player_hand = []
# Deal 3 cards
for i in range(3):
card = random.choice(creatures)
player_hand.append(card)
print(f"Card received: {card['name']}")
print(f"\nTotal cards in hand: {len(player_hand)}")
❌ remove() — Remove by Value
Removes the FIRST occurrence of the given value:
inventory = ["Sword", "Shield", "Potion", "Sword"]
print(inventory) # ['Sword', 'Shield', 'Potion', 'Sword']
inventory.remove("Sword") # Removes the FIRST sword
print(inventory) # ['Shield', 'Potion', 'Sword']
⚠️ Important: If the element is not in the list — it raises an error!
items = ["Sword", "Shield"]
items.remove("Bow") # ❌ ValueError: 'Bow' not in list
Safe approach:
items = ["Sword", "Shield"]
if "Bow" in items:
items.remove("Bow")
else:
print("No bow in inventory")
Example: Removing a defeated card
enemy_hand = [
{"name": "🐲 Dragon", "health": 12},
{"name": "🧙 Mage", "health": 0}, # Defeated!
{"name": "⚔️ Knight", "health": 10}
]
for card in enemy_hand:
if card["health"] <= 0:
print(f"💀 {card['name']} has been defeated!")
enemy_hand.remove(card)
break # Important! Don't modify a list while iterating over it
print(f"Enemy cards remaining: {len(enemy_hand)}")
🎯 pop() — Extract and Remove
Removes an element BY INDEX and RETURNS it:
cards = ["🐲 Dragon", "🧙 Mage", "⚔️ Knight"]
# Take the last card
last_card = cards.pop()
print(f"Took: {last_card}") # ⚔️ Knight
print(cards) # ['🐲 Dragon', '🧙 Mage']
# Take the first card
first_card = cards.pop(0)
print(f"Took: {first_card}") # 🐲 Dragon
print(cards) # ['🧙 Mage']
No argument — removes the last element
With an index — removes the element at that index
Example: Player turn
player_hand = [
{"name": "🐲 Dragon", "attack": 8},
{"name": "🧙 Mage", "attack": 6},
{"name": "⚔️ Knight", "attack": 5}
]
print("Your hand:")
for i, card in enumerate(player_hand):
print(f"{i+1}. {card['name']}")
choice = int(input("\nChoose a card (1-3): "))
selected_card = player_hand.pop(choice - 1)
print(f"\n⚔️ You played: {selected_card['name']}")
print(f"Cards remaining: {len(player_hand)}")
🔍 Checking Membership: in
Before removing or searching — check whether the element is present:
inventory = ["Sword", "Shield", "Potion"]
if "Sword" in inventory:
print("✅ You have a sword!")
else:
print("❌ No sword")
if "Bow" not in inventory:
print("You have no bow")
📏 len() — Number of Elements
Find out how many elements are in the list:
hand = ["🐲 Dragon", "🧙 Mage", "⚔️ Knight"]
print(f"Cards in hand: {len(hand)}") # 3
if len(hand) == 0:
print("Hand is empty!")
Checking for an empty list:
if len(hand) > 0:
print("Has cards")
# Or shorter:
if hand: # Empty list evaluates to False
print("Has cards")
🔄 clear() — Empty the List
Removes ALL elements:
hand = ["🐲 Dragon", "🧙 Mage", "⚔️ Knight"]
print(hand) # ['🐲 Dragon', '🧙 Mage', '⚔️ Knight']
hand.clear()
print(hand) # []
print(f"Cards remaining: {len(hand)}") # 0
📊 Methods Reference Table
| Method | What it does | Example |
|---|---|---|
.append(x) |
Add to the end | hand.append("Sword") |
.remove(x) |
Remove by value | hand.remove("Sword") |
.pop() |
Remove last and return | card = hand.pop() |
.pop(i) |
Remove by index | card = hand.pop(0) |
.clear() |
Empty the list | hand.clear() |
len(list) |
Number of elements | len(hand) |
x in list |
Check membership | "Sword" in hand |
💪 Practical Examples
Example 1: Inventory
inventory = []
# Add items
inventory.append("Sword")
inventory.append("Shield")
inventory.append("Potion")
print(f"Inventory: {inventory}")
# Use a potion
if "Potion" in inventory:
inventory.remove("Potion")
print("💊 Potion used!")
print(f"Remaining: {inventory}")
Example 2: Action Queue
actions_queue = ["attack", "defend", "heal", "power_attack"]
while len(actions_queue) > 0:
current_action = actions_queue.pop(0) # Take the first
print(f"⚔️ Executing: {current_action}")
print("All actions executed!")
Example 3: Card Deck
deck = [
{"name": "🐲 Dragon", "attack": 8},
{"name": "🧙 Mage", "attack": 6},
{"name": "⚔️ Knight", "attack": 5},
{"name": "🧚 Fairy", "attack": 3}
]
hand = []
# Draw 2 cards from the deck
for i in range(2):
card = deck.pop(0) # Take the top card from the deck
hand.append(card) # Add to hand
print(f"Drew card: {card['name']}")
print(f"\nCards in deck: {len(deck)}")
print(f"Cards in hand: {len(hand)}")
⚠️ Important Gotchas
1. Don’t modify a list while iterating over it
# ❌ WRONG!
items = ["A", "B", "C", "D"]
for item in items:
if item == "B":
items.remove(item) # May skip elements!
# ✅ CORRECT: iterate over a copy
items = ["A", "B", "C", "D"]
for item in items[:]: # [:] creates a copy
if item == "B":
items.remove(item)
2. remove() vs pop()
# remove() — deletes by VALUE
hand = ["Sword", "Shield", "Potion"]
hand.remove("Shield") # Removed "Shield"
# pop() — deletes by INDEX
hand = ["Sword", "Shield", "Potion"]
hand.pop(1) # Removed element at index 1 (also "Shield")
3. Methods modify the list in place
numbers = [1, 2, 3]
numbers.append(4) # Modifies numbers directly
print(numbers) # [1, 2, 3, 4]
# Methods do NOT return a new list (except pop)
result = numbers.append(5)
print(result) # None
🎯 Summary
Core methods:
- ✅ .append(x) — add an element
- ✅ .remove(x) — remove by value
- ✅ .pop() — take and remove
- ✅ .clear() — empty the list
- ✅ len(list) — get the size
- ✅ x in list — check membership
Remember:
- Methods are called with dot notation: list.method()
- append adds to the end
- remove deletes by value (first occurrence)
- pop deletes by index and returns the element
- Check membership before removing!
- Use len() to check the size of a list
💬 Comments (0)
No comments yet
Be the first to share your opinion about this article!