Warmup

  • Create a list of 4 songs.
  • Print the second song.
  • Add a song using .append()
  • Remove a song using .remove()

Agenda

  • Permission forms
  • CodeHS Class
  • Lesson 3.2

CodeHS Classes

Lesson 3.2 – Lists: Slicing & Methods

What we’ll learn today

  • How to slice lists (sub-lists)
  • Useful list methods (append, insert, remove, pop, len)
  • Practice using slices and methods

Quick Review

  • What is a list?
  • How do you access a single element from a list?

Slicing Basics

  • A slice is a sub-list taken from a list
  • Syntax: list[start:end]
  • Example:
nums = [10, 20, 30, 40, 50]
print(nums[1:4])   # [20, 30, 40]

Slicing Practice

  • What will this print?
letters = ["a", "b", "c", "d", "e"]
print(letters[:3])
print(letters[2:])

List Methods – append

  • Adds to the end of the list
colors = ["red", "green"]
colors.append("blue")
print(colors)   # ["red", "green", "blue"]

Try It

  • Start with [1, 2, 3]
  • Append the number 4
  • What does the list look like?

List Methods – insert

  • Adds at a specific position
nums = [1, 2, 4]
nums.insert(2, 3)
print(nums)   # [1, 2, 3, 4]

List Methods – remove

  • Removes the first matching value
fruits = ["apple", "banana", "cherry"]
fruits.remove("banana")
print(fruits)   # ["apple", "cherry"]

List Methods – pop

  • Removes item at an index (last by default)
nums = [10, 20, 30]
nums.pop()
print(nums)   # [10, 20]

Length of a List

  • Use len() to count elements
pets = ["dog", "cat", "hamster"]
print(len(pets))   # 3

Class Question

  • What’s the difference between remove and pop?

Mini Challenge

  1. Start with [5, 10, 15, 20]
  2. Append 25
  3. Insert 0 at the beginning
  4. Remove 15
  5. Print the list
  6. print a slice of the list from (start at) index 1 to (stop at) index 3