Lists and For Loops

CDS1010: Week 3A
Wiedemann • Fall 2025

Lists

  • list: an ordered collection of items defined with [ ]
  • index: numeric position (with first item at index 0)
  • len(x): number of items in x
  • Negative indices count backwards, from the end
  • in / not in: test inclusion/exclusion
colors = ["red", "blue", "green", "yellow"]
print(colors[0])   # red
print(colors[1])   # blue
print(colors[-1])  # yellow
print(len(colors)) # 4
print("red" in colors)  # True
print("purple" in colors)  # False

Strings as Sequences

  • Strings are sequences of characters: we can use len(), indexing, and membership on strings too
word = "hello"
print(word[0])  # "h"
print(word[-2])  # "l"
print(len(word))  # 5
print("h" in word)  # True

range()

  • range(stop): starts at 0, stops before stop
  • range(start, stop): starts at start, stops before stop
  • range(start, stop, step): starts at start, stops before stop, counting by step
for i in range(5):
    print(i)  # 0..4

for i in range(2, 7):
    print(i)  # 2..6

for i in range(1, 10, 2):
    print(i)  # 1, 3, 5, 7, 9

For Loops

  • The loop variable takes each value of the iterable in turn
  • We can use for with any of our iterable types: range(...), lists, strings
for count in range(3):
    print(count)
colors = ["red", "blue", "green", "yellow"]
for color in colors:
    print(color)
word = "hello"
for letter in word:
    print(letter)

Building Lists with append()

  • list.append(x) adds an item to the end of a list
  • This is useful for building lists while the program is running
items = []
for i in range(3):
    items.append(i)
print(items)  # [0, 1, 2]

Random Selection

  • We can get random items from a list in multiple ways:
    • if we need the index, we can use our familiar random.randint to get a random index, then use than index to get an item
    • if we don't need the index, we can use random.choice to get a random item directly
import random
colors = ["red", "blue", "green", "yellow"]

# If we need the index:
random_index = random.randint(0, len(colors) - 1)
print(colors[random_index])

# If we don't need the index:
print(random.choice(colors))