๐Ÿ Python for Teens & Beginners ยท Lesson 6 of 7

Lists

Google Classroom

Many values in one variable.

A list

fruits = ["apple", "banana", "cherry"]
print(fruits[0])   # apple
print(fruits[-1])  # cherry
print(len(fruits)) # 3

Indexes 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 fruitsTrue 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

  1. Make a list of 5 favorite movies and print each with a for loop
  2. Ask for 4 test scores, store them in a list and print the average
  3. Add and remove items from a shopping list
  4. Check whether a word the user types is in your list

โœ๏ธ Run Python in your browser, no install โ†—

๐Ÿง  Quick quiz

Answer all 4 questions correctly to mark this lesson as done.

1. fruits = ["a", "b", "c"]. What is fruits[1]?
2. How do you add to the end of a list?
3. What does len([4, 5, 6]) return?
4. What does fruits[-1] give?

0 of 4 correct