Extract the first N and last N elements of a list by building two new lists with index loops. The replay shows each append growing the output lists one element at a time, making the index arithmetic visible.

By hand

The Pythonic way

Slice syntax values[:n] and values[-n:] express the same selections in one token each. Negative indices count from the end, so no length arithmetic is needed.

naive.py
values = [10, 20, 30, 40, 50, 60, 70, 80]
n = 3
first_n = []
last_n = []
for i in range(n):
    first_n.append(values[i])
for i in range(n):
    last_n.append(values[len(values) - n + i])
print('RESULT:', (first_n, last_n))
library.py
values = [10, 20, 30, 40, 50, 60, 70, 80]
n = 3
first_n = values[:n]
last_n = values[-n:]
print('RESULT:', (first_n, last_n))
RESULT: ([10, 20, 30], [60, 70, 80])

Implementation notes

  • first_n and last_n grow visibly in the replay: [][10][10, 20][10, 20, 30] and [][60][60, 70][60, 70, 80].
  • values[-n:] is equivalent to values[len(values)-n:]; Python resolves the negative index internally, which is exactly what the naive loop computes by hand.
  • The two loops share the variable i; its value resets to 0 at the start of the second loop, which is visible in the trace.