Array slicing involves taking a subset from an array and allocating a new array with those elements.
In Python 2.7 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 from start_index onwards 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:
- allocating a new list
- 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:
But a bit harder to see when you don't save the result of the slice to a variable:
So keep an eye out. Slice wisely.
See also:
Interview coming up?
Get the free 7-day email crash course. You'll learn how to think algorithmically, so you can break down tricky coding interview questions.
No prior computer science training necessary—we'll get you up to speed quickly, skipping all the overly academic stuff.
No spam. One-click unsubscribe whenever.
You're in! Head over to your email inbox right now to read day one!