Lecture 6: Loops, Lists, and Basic Knitting¶
Welcome! In this lecture, we'll learn two fundamental programming concepts: loops (repeating actions) and lists (collections of data). These are essential for working with patterns and generating knitting instructions. By the end of these lectures, you will be able to:
- use
forloops to repeat actions - create and manipulate lists
- access list elements using indexing
- check membership with the
inoperator
These (plus the conditionals) are what you need for HW2!
In addition, we will cover some basics about knitting. Although we won't be doing knitting in lecture (if you want to try it, come find me in office hours), we will watch a couple videos of hand knitting and also learn about the machine's capabilities and constraints.
Why Do We Need Loops?¶
Imagine you're knitting a scarf that's 200 rows long. Your pattern might say:
Row 1: Knit all stitches
Row 2: Knit all stitches
Row 3: Knit all stitches
...(197 more times)
That would be tedious to write out! Instead, knitting patterns use repetition:
Repeat: Knit all stitches (200 times)
Programming has the same need. Instead of writing the same code over and over, we use loops to repeat actions.
The for Loop¶
The for loop repeats a block of code a specific number of times. It's perfect when you know exactly how many repetitions you need.
Basic syntax:
for variable in sequence:
# code to repeat
# (this is the loop body)
The most common way to use a for loop is with the range() function.
The range() Function¶
The range() function generates a sequence of numbers. It has three forms:
range(stop)- generates numbers from 0 (inclusive) up tostop(exclusive)
# range(stop) - counts from 0
print("Counting from 0 up to 4:")
for i in range(5):
print(i)
Counting from 0 up to 4: 0 1 2 3 4
range(start, stop)- generates numbers fromstart(inclusive) up tostop(exclusive)
# range(start, stop)
print("Counting from 10 up to 14:")
for i in range(10, 15):
print(i)
Counting from 10 up to 14: 10 11 12 13 14
range(start, stop, step)- generates numbers fromstart(inclusive) up tostop(exclusive), incrementing by step
# range(start, stop, step)
print("Counting every other number:")
for i in range(0, 10, 2):
print(i)
Counting every other number: 0 2 4 6 8
And the step parameter doesn't have to be positive:
# You can count backwards too!
print("Counting down:")
for i in range(10, 0, -1):
print(i)
Counting down: 10 9 8 7 6 5 4 3 2 1
Loop Variable¶
The variable after for (often called i, but can be any name) takes on each value in the sequence, one at a time. This is called the loop variable.
You can use this variable inside the loop body:
# Using the loop variable
print("Row numbers:")
for row in range(1, 11): # recall by default start is 0
if row % 2 == 0:
print(f"Row {row}: Knit all stitches")
else: # which means row % 2 is 1
print(f"Row {row}: Purl all stitches")
Row numbers: Row 1: Purl all stitches Row 2: Knit all stitches Row 3: Purl all stitches Row 4: Knit all stitches Row 5: Purl all stitches Row 6: Knit all stitches Row 7: Purl all stitches Row 8: Knit all stitches Row 9: Purl all stitches Row 10: Knit all stitches
Question, is row a local variable (local to the for loop)?
row
The loop variable doesn't have to be used in the loop body:
print("Repeat:")
for i in range(5):
print("Knit all stitches")
print("Purl all stitches")
Repeat: Knit all stitches Purl all stitches Knit all stitches Purl all stitches Knit all stitches Purl all stitches Knit all stitches Purl all stitches Knit all stitches Purl all stitches
In fact, you can use _ in Python for any variable that's not used.
print("Repeat:")
for _ in range(5):
print("Knit all stitches")
print("Purl all stitches")
Repeat: Knit all stitches Purl all stitches Knit all stitches Purl all stitches Knit all stitches Purl all stitches Knit all stitches Purl all stitches Knit all stitches Purl all stitches
Lists in Python¶
So we just saw for loops that iterate over a sequence. There are many things that are considered sequences in Python, and one of them is a list.
A list is a collection of values. Think of it like a shopping list, a to-do list, or a pattern sequence. It's an ordered collection of items.
In knitting terms, you might have:
- A list of colors in your project
- A list of stitch types in a row
- A list of measurements
Lists are created using square brackets [], with items separated by commas.
colors = ["blue", "green", "yellow", "red"] # list of strings
colors
['blue', 'green', 'yellow', 'red']
single_item = ["knit"] # list with one element is allowed too
single_item
['knit']
stitch_counts = [20, 22, 20, 18, 20]
stitch_counts
[20, 22, 20, 18, 20]
mixed_list = ["worsted", 4, True, 3.5] # Lists can hold different types!
mixed_list
['worsted', 4, True, 3.5]
empty_list = []
empty_list
[]
# this `list` constructor also creates an empty list
list()
[]
There's no limit to how mixed the list can be.
more_mixed_list = [mixed_list, range, empty_list, 116, 'ribbing']
more_mixed_list
[['worsted', 4, True, 3.5], range, [], 116, 'ribbing']
List Indexing¶
Each item in a list has a position called an index. Python uses zero-based indexing, meaning the first item is at index 0, the second at index 1, and so on.
You access list elements using square brackets: list_name[index]
# Recall that we defined the colors list before: ["blue", "green", "yellow", "red"]
print(f"First color: {colors[0]}") # blue
print(f"Second color: {colors[1]}") # green
print(f"Third color: {colors[2]}") # yellow
print(f"Fourth color: {colors[3]}") # red
First color: blue Second color: green Third color: yellow Fourth color: red
You can also use negative indices to count from the end:
-1is the last item-2is the second-to-last item- And so on...
print(f"Last color: {colors[-1]}") # red
print(f"Second to last: {colors[-2]}") # yellow
Last color: red Second to last: yellow
What happens if you try to index colors[5]?
colors[5]
List indices are only valid up to the size / length of the list (exclusive, because indices start from 0). This is why it's useful to check how long the list is before trying indexing into it.
Poll Time!¶
Recall that we created a variable more_mixed_list which is a list mixing other lists and data types:
[['worsted', 4, True, 3.5], range, [], 116, 'ribbing']
What will more_mixed_list[2][-1] evaluate to?
List Length¶
The len() function returns the length of a list, which is the number of items in that list:
print(f"Number of items in colors: {len(colors)}") # 4
print(f"Number of items in more_mixed_list: {len(more_mixed_list)}") # 5
Number of items in colors: 4 Number of items in more_mixed_list: 5
print(f"Empty list has length 0: len(empty_list) = {len(empty_list)}")
Empty list has length 0: len(empty_list) = 0
This is useful for writing for loops that iterate over the list (which is a sequence).
Iterating Over Lists¶
We can use range to generate a sequence of valid indices that is [0, n) if n is the length of the list and use a for loop to iterate over the list and access each of the items in order.
print("All colors:")
for i in range(len(colors)):
print(f"Color {i}: {colors[i]}")
All colors: Color 0: blue Color 1: green Color 2: yellow Color 3: red
You can also use a for loop directly with a list with the in keyword, without needing range(). This is often cleaner and more readable:
print("All Colors:")
for color in colors:
print(color)
All Colors: blue green yellow red
Use direct iteration when you only need the values. Use indices when you need to know the position or modify the list.
But of course, there's also the best (or could be worst?) of both worlds: enumerate if you do need both indices and the items.
for i, color in enumerate(colors):
print(f"Item at index {i} in list colors is {color}")
Item at index 0 in list colors is blue Item at index 1 in list colors is green Item at index 2 in list colors is yellow Item at index 3 in list colors is red
Question: what is i, color? Recall when we had multiple return values.
The in Keyword¶
The in keyword when not used with for is a membership test operator. It checks if a value exists in a list and returns a boolean (True or False).
"green" in colors
True
"purple" in colors
False
Practice Time¶
We created this list earlier in the notebook
more_mixed_list = [mixed_list, range, empty_list, 116, 'ribbing']
Now let's combine what we learned so far. Write a function that takes a list, iterates through it with a for loop, and prints out the type of each item (you can call the type function on list items).
Recall that the function definition syntax is:
def function_name(parameter1, parameter2, ...):
"""
docstring
"""
{indented function body}
...
And to call that function:
function_name(argument1, argument2, ...)
# TODO: your code here
Modifying Lists¶
Lists are mutable, meaning you can change them after creation.
You can:
- Change individual elements
- Add elements with
.append() - Remove elements (we'll cover this more later)
print(f"Original: {colors}")
Original: ['blue', 'green', 'yellow', 'red']
# Change an element
colors[1] = "purple"
print(f"After change: {colors}")
After change: ['blue', 'purple', 'yellow', 'red']
# Add an element
colors.append("red")
print(f"After append: {colors}")
After append: ['blue', 'purple', 'yellow', 'red', 'red']
Building Lists with Loops¶
You can build lists with loops:
# Generate a list of the first 10 even numbers
evens = [] # Start with empty list
for i in range(10):
evens.append(i * 2)
print(evens)
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
Then we can also use a for loop to calculate the sum of the values in the list.
# Compute the sum of values in the list of first 10 even numbers
total = 0 # Start with zero total
for i in range(len(evens)):
total += evens[i] # this is contraction for total = total + evens[i]
print(total)
90
This pattern of initializing some variable outside a loop and doing something to modify this variable (usually keeping a running sum or adding to a collection) is called the accumulator pattern.
But of course, in the ethos of not reinventing the wheel, you can also simply call the Python-native function sum on the list:
print(sum(evens))
90
Brief Introduction to Knitting¶
Let's take a break from coding and go over some knitting basics. We'll actually use slides here and watch some video clips of hand knitting and machine knitting.
Summary¶
In this lecture, we learned:
forloops repeat code a specific number of timesrange()generates sequences of numbers- Lists store collections of values
- Indexing accesses list elements with
list[index] inoperator checks membership in a list.append()adds elements to lists- basics about knitting
You now have all the tools you need for HW2!