How to Insert Into A List With Slicing In Python
Used to solve Leet Codeās Duplicate Zeroes Puzzle
2 min readSep 14, 2021
The aim of this pageš is to utilize Python slicing to insert a data structure into a list at a given index. Slicing indexes operate as a half-open range ā the first item is included, the last is not:
>>> l = [1,2,3,4]
>>> l[0:1]
[1]
- to insert at a given point, start pointing to the item you want the new structure to start with. then, use the same index value after
- e.g.
[0:0]
to insert a sublist of a random length in the very beginning of a list - the identical values in ([0:0]) are not specifying the span, they only point to the point of entry
- in a stupid example below I want to add
666
at the beginning of the list[1,2,3,4]
>>> l = [1,2,3,4]
>>> l[0:0] = [6,6,6,]
>>> l
[6, 6, 6, 1, 2, 3, 4]
>>>
EXAMPLE: LEET CODEāS DUPLICATE ZEROS PUZZLE
- Iāve used the technique to easily solve https://leetcode.com/problems/duplicate-zeros/ which seems rather challenging in an official solution
- It goes like this: Given a fixed-length integer array
arr
, duplicate each occurrence of zero, shifting the remaining elements to the right. - Note that elements beyond the length of the original array are not written.
- Do the above modifications to the input array in place and do not return anything.
# EXAMPLE
Input: arr = [1,0,2,3,0,4,5,0]
Output: [1,0,0,2,3,0,0,4]
Explanation: After calling your function, the input array is modified to: [1,0,0,2,3,0,0,4]
- I only insert at the point where the zero is found with inserting with slices
- Then, I remove the last item by with
pop()
- Finally, I move the
i
pointer by two to reflect the insertion as we're mutating a collection that's also being iterated upon
# SOLUTION
def duplicateZeros(self, arr: List[int]) -> None:
i = 0
while i < len(arr):
if arr[i] == 0:
arr[i:i] = [0]
arr.pop()
i += 2
else:
i += 1