Unit 4 Β· Lesson 1
Lists: Creating & Accessing
Lists let you store multiple values in a single variable β ordered, indexed, and incredibly flexible.
Create lists with square bracket syntax
Access items with positive and negative indexing
Use
len() to get list sizeExtract portions with slicing
Creating Lists
A list is an ordered collection of items, wrapped in square brackets:
scores = [95, 87, 92, 78, 100]
names = ["Alice", "Bob", "Charlie"]
mixed = ["hello", 42, 3.14, True]
empty = []
Accessing Items by Index
Every item has a position number (index), starting from 0:
colors = ["red", "green", "blue", "yellow"]
print(colors[0]) # "red" (first item)
print(colors[2]) # "blue" (third item)
print(colors[-1]) # "yellow" (last item)
print(len(colors)) # 4
Negative indexing:
-1 is the last item, -2 is second-to-last, etc. This is incredibly handy when you don't know the list's length!Slicing
Extract a portion of a list with list[start:stop]:
nums = [10, 20, 30, 40, 50]
print(nums[1:4]) # [20, 30, 40]
print(nums[:3]) # [10, 20, 30] (first 3)
print(nums[2:]) # [30, 40, 50] (from index 2 on)
print(nums[::2]) # [10, 30, 50] (every other)
Practice Time
Challenges
Challenge 1: Playlist Manager
Guided
Create a list of songs and access specific ones by index.
Instructions: Create a list called
playlist with 5 song names. Set first_song to the first item, last_song to the last (using negative indexing), and count to the total number of songs.Hint 1:
Hint 2:
first_song = playlist[0]Hint 2:
last_song = playlist[-1], count = len(playlist)Challenge 2: First and Last
Guided
Print the first and last item of any list using negative indexing.
Instructions: Given any
items list, set first and last to the first and last elements. Your code must work for any list length.Hint:
first = items[0] and last = items[-1] β works for any list!Challenge 3: Middle Finder
Solo
Find the middle element of a list.
Instructions: Given
Example: [10,20,30,40,50] β middle = 30 (index 2)
data, find the middle element and store it in middle. For odd-length lists, there's one exact middle. For even-length, use the lower-middle index (e.g., for 4 items, use index 1).Example: [10,20,30,40,50] β middle = 30 (index 2)
Hint 1: Middle index =
Hint 2:
len(data) // 2Hint 2:
middle = data[len(data) // 2]Challenge 4: Slice Explorer
Stretch
Use slicing to extract different portions of a list.
Instructions: Given
numbers, use slicing to create: first_three (first 3 items), last_three (last 3 items), every_other (every other item starting from index 0).Hint 1:
Hint 2:
Hint 3:
first_three = numbers[:3]Hint 2:
last_three = numbers[-3:]Hint 3:
every_other = numbers[::2]