Array Slicing

Array slicing involves taking a subset from an array and allocating a new array with those elements.

In Python you can create a new list of the elements in my_list, from start_index to end_index (exclusive), like this:


You can also get everything after start_index by just omitting end_index:


Careful: there's a hidden time and space cost here! It's tempting to think of slicing as just "getting elements," but in reality you are:

  1. allocating a new list
  2. copying the elements from the original list to the new list

This takes time and space, where n is the number of elements in the resulting list.

That's a bit easier to see when you save the result of the slice to a variable:

tail_of_list = my_list[1:]

But a bit harder to see when you don't save the result of the slice to a variable:

return my_list[1:] # whoops, I just spent O(n) time and space!
for item in my_list[1:]: # whoops, I just spent O(n) time and space!

So keep an eye out. Slice wisely.

See also:

Pass Your Interviews with My FREE 7-Day Crash Course

I'll teach you the right way of thinking for breaking down tricky algorithmic coding interview questions you've never seen before.

No prior computer science training necessary—I'll get you up to speed quickly, skipping all the overly academic stuff.

No spam. One-click unsubscribe if you hate it.

What's next?

If you're ready to start applying these concepts to some problems, check out our mock coding interview questions.

They mimic a real interview by offering hints when you're stuck or you're missing an optimization.

Try some questions now

Psst. Pass it on.

. . .