B. Making Lists
๐ฏ Learning Goals
By the end of this lesson, you'll be able to:
- โ Be able to create an empty list
- โ Be able to create a list with items
- โ Understand basic list syntax
Core Concepts
Creating a list
Lists Square brackets [] to create one, and items are comma separated by it.
๐ฆ Analogy: packing a box
You can prepare an empty box first and put things in later, or you can receive a box that already has things in it from the start!
# Empty list
my_list = []
# A list with items
numbers = [1, 2, 3]
names = ["Cheolsu", "Younghee", "Minsu"]
List syntax
| Form | Code | Description |
|---|---|---|
| Empty list | [] |
Add items later |
| Number list | [1, 2, 3] |
Store numbers |
| String list | ["a", "b"] |
Store text |
Things you can put in a list
numbers = [1, 2, 3, 4, 5] # Numbers
names = ["Cheolsu", "Younghee", "Minsu"] # Strings
bullets = [] # Entity objects (added later)
Example Code
from ursina import *
app = Ursina()
# Create an empty list
bullets = []
enemies = []
# A list with items
colors = [color.red, color.blue, color.green]
# Use a color list
for i, c in enumerate(colors):
Entity(model='cube', color=c, position=(i*2, 0, 0))
app.run()
What Happens
Red, blue, and green cubes appear in a row!
Quiz
Quiz: Empty list
What is the correct way to create an empty list?
Show Answer
Answer: A) my_list = []
[]= list (square brackets)()= tuple (parentheses){}= dictionary (curly braces)
List creation practice:
- Empty list:
my_list = - Number list:
numbers = [1,, 3] - A string to wrap it
๐ง Debug Clinic
Problem: TypeError: 'tuple' object...
โ Wrong Code
Cause: Parentheses() used (becomes a tuple)
โ Correct Code
Fix: Square brackets[] Use it!
Try Coding It Yourself
Take what you learned with the blocks and write it yourself in Python code!
Creating an empty list
Create an empty list and add items later.
Example Answer
Result: An empty list [] and a count of 0 are printed!
Creating a number list
Create a list containing numbers!
๐งฉ Key Takeaways
What you learned in this lesson:
| Concept | Description |
|---|---|
| Empty list | [] to create |
| Item list | [1, 2, 3] Form |
| Separator | Comma (,) to separate items |
| Square brackets | [] used (not parentheses) |
Review Checklist
- [ ] Do you know how to create an empty list?
- [ ] Do you understand the difference between square brackets and parentheses?
- [ ] Do you know that you can put different kinds of data in a list?