How to Insert Into A List With Slicing In Python

Used to solve Leet Code’s Duplicate Zeroes Puzzle

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:

  • 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]

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.
  • 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

--

--

Infrastructure Support Engineer/Technical Writer (snowplow.io) with a passion for Python/writing documentation. More about me: https://pavol.kutaj.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Pavol Kutaj

Infrastructure Support Engineer/Technical Writer (snowplow.io) with a passion for Python/writing documentation. More about me: https://pavol.kutaj.com