๐ Python for Teens & Beginners ยท Lesson 6 of 7
Lists
Many values in one variable.
A list
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # apple
print(fruits[-1]) # cherry
print(len(fruits)) # 3Indexes start at 0. -1 is the last item.
Changing a list
| fruits.append("kiwi") | Add to the end |
|---|---|
| fruits.remove("banana") | Remove a value |
| fruits[1] = "mango" | Replace an item |
| fruits.sort() | Sort AโZ or small to big |
| "kiwi" in fruits | True or False |
Looping over a list
scores = [88, 92, 79, 95]
for s in scores:
print(s)
print("Average:", sum(scores) / len(scores))
print("Best:", max(scores))Building a list
names = []
for i in range(3):
names.append(input("A name: "))
print(names)Tip
๐ก IndexError: list index out of range means you asked for an item that doesnโt exist โ like fruits[3] in a list of 3.
โ๏ธ Practice: your turn
- Make a list of 5 favorite movies and print each with a for loop
- Ask for 4 test scores, store them in a list and print the average
- Add and remove items from a shopping list
- Check whether a word the user types is in your list
๐ง Quick quiz
Answer all 4 questions correctly to mark this lesson as done.
0 of 4 correct
All lessons in Python for Teens & Beginners
- ๐ 1. Your first programprint, quotation marks, and error messages
- ๐ฆ 2. Variables and inputStore information and ask the user
- ๐งฎ 3. Math in PythonOperators, division, remainder and powers
- ๐ 4. Conditions: if and elseThe program decides by itself
- ๐ 5. Loops: for and whileRepeat code without copying it
- ๐ 6. ListsMany values in one variable
- ๐ฒ 7. Project: a guessing gameThe computer picks a number, and you guess