List Slicing
Indexing gets you one element out of a list. Slicing gets you a range of them. It comes up all the time in interviews. You might split a list in half or check a string against its reverse. The syntax is short. But a few of the rules surprise people the first time they see them.
Here’s the syntax if that’s all you need:
nums = [0, 1, 2, 3, 4, 5]
print(nums[1:4]) # [1, 2, 3], from index 1 up to (not including) 4
print(nums[:3]) # [0, 1, 2], the first 3
print(nums[-2:]) # [4, 5], the last 2
print(nums[:-1]) # everything except the last one
print(nums[::2]) # [0, 2, 4], every other item
print(nums[::-1]) # [5, 4, 3, 2, 1, 0], reversed
copy = nums[:] # a shallow copy of the whole listSlice basics: start:stop:step
O(k)You write a slice as a[start:stop:step]. It returns a new list with the elements from start up to (but not including) stop. It moves step elements at a time. If you leave out start, it starts at the beginning. If you leave out stop, it goes to the end. If you leave out step, it uses 1.
letters = ["a", "b", "c", "d", "e", "f"]
print(letters[1:4])
print(letters[:3])
print(letters[3:])
print(letters[:])step goes in the third slot. The first line below grabs every second element starting at index 1. The second line grabs every third element from the whole list:
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(numbers[1:8:2])
print(numbers[::3])Note
stop is never included. a[1:4] returns 3 elements at indices 1, 2, and 3. It never includes the element at index 4. range() follows the same rule. It’s worth learning this once so you don’t have to work it out every time you write a slice.
Negative indices and negative steps
O(n)A negative index counts from the end instead of the start. a[-1] is the last element. A negative number in a slice works the same way. It marks a position counted from the end:
letters = ["a", "b", "c", "d", "e"]
print(letters[-1])
print(letters[-3:])
print(letters[:-2])
print(letters[::-1])letters[::-1] is the usual one-liner for reversing a list. A step of -1 moves backward from the end to the start. Compare it to list.reverse(). That one reverses the list in place instead of returning a new list:
original = [1, 2, 3]
reversed_copy = original[::-1]
print(original, reversed_copy)
original.reverse()
print(original)Note
[::-1] makes a copy. reverse() changes the list. After reversed_copy = original[::-1], original hasn’t changed. It still prints in its starting order next to the new reversed list. original only changes once you call original.reverse(). Use [::-1] when you need to keep the original order too. Use reverse() when you don’t.
Why out-of-range slices never raise
no errorSometimes a slice’s start or stop goes past the end of the list or before the beginning. Python moves it back to the edge of the list instead of raising an error:
letters = ["a", "b", "c"]
print(letters[10:20])
print(letters[-100:2])
print(letters[1:100])A single index can’t be moved back like that. If it’s out of bounds, you get an error:
letters = ["a", "b", "c"]
try:
print(letters[10])
except IndexError as e:
print(f"IndexError: {e}")Note
This causes a lot of bugs that are hard to spot. If you make a typo in a slice, Python just returns a shorter list or an empty one. You won’t get an error. Remember to check len() on the result if you expect a slice to be a certain length.
Slices are shallow copies
watch outa[:] makes a new list. If you append to the new list, the original doesn’t change. But the elements themselves aren’t copied. The new list just points at the same elements. If an element can be changed in place, like a nested list, both lists end up pointing at the same object:
inner = [1, 2]
original = [inner, "x", "y"]
shallow = original[:]
shallow.append("z")
shallow[0].append(3)
print(original)
print(shallow)Note
shallow.append("z") only changed shallow. It added a new slot to the copy’s own list. But shallow[0].append(3) changed the inner list itself. original[0] and shallow[0] both point at that same inner list. That’s why the 3 shows up in both. Use copy.deepcopy() instead of a slice if you need the nested lists copied too.
Slice assignment
You can put a slice on the left side of = too. That replaces the elements in that range with whatever you assign. The new elements don’t have to be the same length as the old ones:
numbers = [0, 1, 2, 3, 4, 5]
numbers[1:3] = [10, 20, 30]
print(numbers)If you assign an empty list to a slice, you delete that range. You can also use del on a slice to do the same thing:
numbers = [0, 1, 2, 3, 4, 5]
numbers[1:4] = []
print(numbers)numbers = [0, 1, 2, 3, 4, 5, 6]
del numbers[::2]
print(numbers)Note
del numbers[::2] removes every other element, starting at index 0. You don’t need a loop. Slice assignment can change the list’s length, though. Be careful if you loop over indices and assign to a slice inside that same loop. The indices can shift while the loop is still running.
Where list slicing shows up in interviews
Slicing is great for quickly checking your answer. It’s usually not the solution an interviewer is looking for, though:
- Valid Palindrome can be checked in one line with
s == s[::-1]once you’ve cleaned up the string. Most interviewers want the two-pointer version instead. It uses O(1) extra space and shows you understand the pattern. Still,s[::-1]is the fastest way to double-check your two-pointer answer. - Reorder List has you reverse the second half of a linked list. You can do the same thing on a plain Python list. Slice the list in half, then reverse one half with
[::-1].