Why does appending inside `range(len(L))` terminate while appending over L itself loops forever, and how does extend differ from append?
Short drills on what this video just taught. Write the code, run the checks, and reveal the answer only if you are stuck.
Start from values = [1, 2, 3, 4]. Loop over range(len(values)) and, on each pass, append the loop variable to values. Then assign the final contents of values to final_list.
This loop is safe to run — but try to predict how many passes it makes first.
Appending while looping over range(len(L))
Trace L = [1, 2, 3, 4] through for i in range(len(L)): L.append(i), writing the printed list after each of the four passes and the fixed sequence 0, 1, 2, 3 built up front.
The non-terminating loop over the elements
Write the for e in L version with L.append(i) and a counter inside, trace the first three passes, and record that e stays four elements behind the growing end.
extend against the concatenation L1 + L2
Write L1.extend([0, 6]) turning [2, 1, 3] into [2, 1, 3, 0, 6] beside L3 = L1 + L2, and record which names change and which stay untouched.
Counting the elements extend adds
Record that L2.extend([[1, 2], [3, 4]]) lengthens L2 by two elements, the two inner lists, with the outer brackets of the argument stripped.