Rotating the Rota With push() and shift()
In this lesson, you ported the Monday script’s first step, which moves last week’s person from the front of the rota to the back, and met the four methods that add and remove items at the two ends of an array.
- The list carries over as an array literal, with a
const. Theconstfixes the name, not the array’s contents, so the rotation can still change the array. - Python’s
append()is JavaScript’s.push(), which adds an item to the end of the array. - Python’s
pop()can take a position, but JavaScript’s.pop()takes none: it always takes the last item, so the natural port,rota.pop(0), takes Bea. Taking from the front has a method of its own,.shift(), which does what Python’spop(0)does. - Watch out for Python’s method names: an array has no
append()method, so callingrota.append(...)fails with “TypeError: rota.append is not a function”, and.push()is the name to write instead. - When the rotation line runs,
.shift()hands back the item it took off, as Python’spop(0)does..push()hands back the array’s new length, where Python’sappend()changes the list and hands backNone. .unshift()puts an item at the front, as Python’sinsert(0, x)does, and like.push()it hands back the new length, whereinsert()hands backNone.- Watch out at an empty array: there,
.pop()and.shift()hand backundefined, where Python’spop()raises anIndexError, and the rotation’s other method then adds thatundefinedto the rota: check the length before you rotate.
Here’s the rotation step of the Python script, monday_rota.py:
rota = ["Marta", "Dev", "Sam", "Ines", "Kofi", "Bea"]
rota.append(rota.pop(0))
print(f"On call this week: {rota[0]}")
print(rota)