C. Adding Items with append()
๐ฏ Learning Goals
By the end of this lesson, you'll be able to:
- โ
append()function to add items - โ Be able to add bullets/enemies to a list in a game
- โ Understand how to call methods
Core Concepts
What is append()?
append() function adds an item to the end of a list.
๐ฌ Analogy: a mailbox
Just like MailboxLike putting a letter into a mailbox! A new letter is always added at the very back.
fruits = ["Apple", "Banana"]
fruits.append("Orange")
# fruits = ["์ฌ๊ณผ", "๋ฐ๋๋", "์ค๋ ์ง"]
Syntax
- Dot (
.) connects it to the list - The item to add goes inside the parentheses
Using it in games
bullets = []
# Add each time a bullet is fired
bullet = Entity(model='cube')
bullets.append(bullet) # Add to the list!
Example Code
from ursina import *
app = Ursina()
# Empty list
cubes = []
# Add 5 with a loop
for i in range(5):
cube = Entity(
model='cube',
color=color.red,
position=(i*2, 0, 0)
)
cubes.append(cube) # Add to the list!
print(f"Cube count: {len(cubes)}") # 5
app.run()
What Happens
Five cubes are stored in the list!
Quiz
Quiz: Adding items
What is the name of the function that adds an item to a list?
Hint: my_list.___("์ ํญ๋ชฉ")
Hint: my_list.___("์ ํญ๋ชฉ")
Show Answer
Answer: append
append means "to add."
It adds a new item to the end of the list!
append() practice:
fruits = ["์ฌ๊ณผ", "๋ฐ๋๋"] Given a list:
- "ํฌ๋"to the end of fruits:
fruits.("ํฌ๋")โ["์ฌ๊ณผ", "๋ฐ๋๋", "ํฌ๋"] - With a dot (.) connect the name and the function
- The added item is always positioned there
๐ง Debug Clinic
Problem: AttributeError: 'NoneType' object has no attribute 'append'
โ Correct Code
Fix: You have to create an empty list first!Try Coding It Yourself
Take what you learned with the blocks and write it yourself in Python code!
Adding with append()
Add items one by one to an empty list.
Example Answer
Result: ['์ฌ๊ณผ', '๋ฐ๋๋', '์ค๋ ์ง'] is printed!
Adding with a loop
Try using a loop together with append()!
๐งฉ Key Takeaways
What you learned in this lesson:
| Concept | Description |
|---|---|
| append() | Add an item to the end of a list |
| Syntax | list.append(item) |
| Position | Always added at the very back |
| Caution | You have to create the list first |
Review Checklist
- [ ]
append()Can you explain the role of the function? - [ ] Do you know how to connect a list and a function with a dot (.)?
- [ ] In a loop,
append()can you make use of it?