Loop Enumerate
- Reminder: We can refer to specific elements of a list using an index
- Begin counting at 0
my_list[1]
is second item on the list.
- Indexes can be variables:
my_list[x]
- Three ways to iterate over a list:
for value in lst:
print(value)
for index in range(0, len(lst)):
print(f"{index:03d}: {lst[index]}")
for value, index in lst.enumerate():
print(f"{index:03d}: {value}")
- The basic
foreach
loop is useful when we need the values only. range
andenumerate
are useful when we also need the index.- Switch to In-Class 11
Transforming Sequences
- In-Class 12
first_last
. (Just modify existing list.) - Build a new list.
- Show
cost_with_tax
- In-Class 12
double_all
- show corresponding list comprehension
- Show
- Conditionally apply rule
- Conditionally add values to the new list
- Select positive numbers
- Concatenate vs append
- Subsequences/slice
- Don’t mutate a list as you iterate through it.