Skip to content

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

list name.append(to add Item)
  • 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.___("์ƒˆ ํ•ญ๋ชฉ")
Show Answer

Answer: append

append means "to add." It adds a new item to the end of the list!

my_list.append("new item")

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'

โŒ Wrong Code

bullets.append(bullet)  # bullets doesn't exist!
Cause: The list wasn't created

โœ… Correct Code

bullets = []  # Create an empty list first
bullets.append(bullet)
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
fruits = []
fruits.append('Apple')
fruits.append('Banana')
fruits.append('Orange')
print(fruits)

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?