Changing the Rota in Place With splice()
In this lesson, you took Sam, who’s on leave, out of the middle of the rota, put the new hire Lena in after this week’s person, and met the one JavaScript method that does both.
- JavaScript has a
deleteoperator, so Python’sdel rota[1]ports asdelete rota[1];. It runs with no error, but it works like Python’sdelon a dict:del slots[1]on{0: "Dev", 1: "Sam", 2: "Ines"}takes out one key, keeps keys 0 and 2, and the dict’s length drops to 2. deletetakes position 1 out the same way and renumbers nothing: Marta is still at position 5.deletenever changes an array’s length: it stays 6, where Python’slen()gives 5.- The array is left with a hole, or empty slot: a position with no item in it. JavaScript logs it
as
<1 empty item>, and.join()turns it into an empty string, so the next three weeks printDev, , Ines. delon a list anddeleteboth clear a position, but onlydelon a list closes the gap, so JavaScript developers don’t usedeleteon arrays.- To remove, insert or replace items in the middle of an array, call
.splice()and read its arguments as start, how many to remove, what to put in.rota.splice(1, 1)cuts out Sam and closes the gap. .splice()hands back what it cut out, in an array: here,[ 'Sam' ]. When you don’t need it, call.splice()on a line of its own, like.push().- JavaScript arrays have no insert method:
rota.splice(1, 0, "Lena")starts at 1, removes 0 and puts in Lena, as Python’srota.insert(1, "Lena")does. - If two weeks change hands, Python’s slice assignment swaps in the new names, and that’s
.splice()too:rota[1:3] = ["Noor", "Rui"]becomesrota.splice(1, 2, "Noor", "Rui"), which hands back[ 'Lena', 'Ines' ]. Python passes the new names as one list, but.splice()takes each one as an argument. Note the second number: Python’s slice stops before position 3, but the second number in.splice()counts how many to remove, 2. .slice()and.splice()are one letter apart:.slice()copies a range and leaves the array alone, and.splice()changes the array itself.
Here’s the team lead’s Python step:
rota = ["Dev", "Sam", "Ines", "Kofi", "Bea", "Marta"]
del rota[1]
print(rota, len(rota))
print(", ".join(rota[:3]))