Day 8: Introduction to Lists

Hey students, welcome to Week 2! We're diving into lists, which are like containers for multiple items. Start by creating an empty list: favorites = []—square brackets make a list. We use a for loop (from Day 5) with range(3) to repeat three times. Inside, input() gets a food name, stored in food. Then, favorites.append(food) adds it to the end of the list—append() is a list method that grows the list dynamically.

Create a script that asks the user for three favorite foods, stores them in a list, and prints the list along with the first and last items.

favorites = []
for _ in range(3):
    food = input("Enter a favorite food: ")
    favorites.append(food)
print("Your favorites:", favorites)
print("First:", favorites[0])
print("Last:", favorites[-1])

After the loop, print("Your favorites:", favorites) shows the whole list. Access items by index: favorites[0] is the first (indexes start at 0), favorites[-1] is the last (negative indexes count from the end). Run it: Enter "Nshima", "Rice", "Fish"—prints the list, first as "Nshima", last as "Fish".

In your 10-15 minutes, try adding more items or printing the second one ([1]). Lists are mutable (changeable), perfect for collections like scores or names. This builds on inputs—now store multiples! Keep going; you're organizing data now.

Key Concepts:

  • List: An ordered, mutable collection of items (e.g., numbers, strings) enclosed in square brackets []. Can hold duplicates and mixed types.
  • Indexing: Accessing list elements by position, starting at 0 (e.g., list[0] for first). Negative indexes like -1 access from the end.
  • .append(): A list method that adds an item to the end of the list, increasing its length.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top