Skip to content
Complexity

Is slicing O(n) in Python?

Is slicing O(n) in Python? Yes: lists, strings, tuples and bytes copy the slice, so the cost is O(k) for k elements. Here is how that quietly turns fast algorithms slow, and how to avoid it.

The short answer to "is slicing O(n) in Python" is yes. A slice of a list, string, tuple or bytes object copies its k elements into a brand new object, so it costs O(k) time and O(k) memory, which is O(n) when you slice most of the sequence. The cost hides inside syntax that looks like a lookup.

That hidden cost is responsible for a surprising number of "my binary search is slow" and "my recursion times out" bug reports. The slicing itself is rarely the problem. The problem is an algorithm whose analysis assumed a step was O(1), written in a language where that step is not.

How much does a Python slice actually cost?

A slice costs time and memory proportional to the number of elements it returns, not the size of the sequence it came from. For a list, CPython allocates a new list object, copies k pointers into it, and increments the reference count of each element it copied. For a string or bytes object it allocates a new buffer and copies k characters with a memcpy. Neither is a view of the original.

Here is the framing I use. Indexing is pointing at a page in a book. Slicing is feeding pages through a photocopier, and the machine charges by the page. When you write a[mid:] you have not told Python "look over there", you have said "make me a second book". Once you think of it as a photocopy, the questions answer themselves: how many pages, and how many times are you going to run the machine?

A few details worth keeping straight:

  • a[i:j] costs O(j - i), clamped to the actual length. It is not O(n) unless the slice is a large fraction of n.
  • a[:3] is O(1) in any practical sense, because k is a constant. People over-apply the rule and avoid slices that are perfectly cheap.
  • a[::2] copies about n/2 elements, and a[::-1] copies all n. Step does not reduce the cost to O(1); it only changes which elements get copied.
  • The copy is shallow. A list of a million large objects copies a million pointers (about 8 MB on a 64-bit build), not the objects themselves.
  • As a CPython implementation detail, a full-length slice of a string or tuple can return the same object, since both are immutable. Do not build an analysis on that.

None of this is exotic. It is the same reason list.pop(0) is slow: a cheap-looking operation whose real work is moving a block of memory.

Why does slicing inside a loop or recursion hurt so much?

Because a slice only changes your complexity class when it sits inside something you assumed was O(1), and recursion on halves or on "the rest of the list" is exactly that. A copy of size n/2 at every level turns an O(log n) algorithm into an O(n) one. Here is a concrete case.

Take a sorted list of 1,000,000 integers and search it for a target. Here are two versions of the same idea.

def search_copy(a, target):
    if not a:
        return False
    mid = len(a) // 2
    if a[mid] == target:
        return True
    if a[mid] < target:
        return search_copy(a[mid + 1:], target)
    return search_copy(a[:mid], target)


def search_idx(a, target):
    lo, hi = 0, len(a) - 1
    while lo <= hi:
        mid = (lo + hi) // 2
        if a[mid] == target:
            return True
        if a[mid] < target:
            lo = mid + 1
        else:
            hi = mid - 1
    return False

Both halve the problem, so both take about 20 steps for a million elements (log2 of 1,000,000 is just under 20). The difference is what each step does. The index version updates two integers. The copy version builds a new list of roughly half the remaining size: about 500,000 elements on the first call, then 250,000, then 125,000, and so on. That series sums to nearly 1,000,000 elements copied per search. The recurrence is T(n) = T(n/2) + O(n), which solves to O(n), not O(log n).

On a typical laptop, copying a list pointer and bumping its refcount costs on the order of a nanosecond or two per element, so one search spends roughly 1 to 3 milliseconds in copying alone and allocates several megabytes along the way. The index version finishes in a few microseconds. Treat the exact figures as an order of magnitude and measure on your own machine, but the ratio is around a thousand. Run 1,000 queries and you are comparing about two seconds with about three milliseconds. Worse, the copying version has no advantage over just calling target in a, which is also O(n) and needs no recursion at all.

The same trap appears in other shapes:

  • Process the rest of the list. A function that handles a[0] and then recurses on a[1:] copies n-1, then n-2, then n-3 elements. For n = 10,000 that is about 50 million element copies, and you will probably hit the recursion limit first (see why you get maximum recursion depth exceeded).
  • The slice-as-queue. Writing a = a[1:] in a loop to "pop from the front" is O(n) per iteration and O(n squared) overall. A collections.deque does the same job in O(1) per pop.
  • Divide and conquer that already copies. A merge sort written with slices is still O(n log n), because merging was already linear per level. The slices add a constant factor and extra allocation, not a new complexity class. This is the case where slicing is mostly harmless.

The pattern to internalise: slicing is dangerous exactly where the algorithm's whole point was to avoid touching most of the data. Binary search, recursive tree-like descents and sliding windows all fall in that category.

Are string slices cheaper than list slices?

Per element, yes by a good margin, because a string slice is a single memcpy of bytes with no refcounting. Asymptotically they are identical: O(k). The small constant lulls people into believing string slicing is free, and then the quadratic or cubic structure of their code arrives anyway.

Consider the classic "find the longest palindromic substring" brute force. It tries every pair (i, j), slices s[i:j], and compares it with its reverse. For a string of length n there are n(n + 1)/2 substrings, and the total number of characters copied across all of them is n(n + 1)(n + 2)/6. For n = 2,000 that is about 2 million slices and 1.34 billion characters copied, before a single comparison, and the reversed copy and equality check roughly triple the work. That runs in a second or two and feels survivable. At n = 20,000 the character count grows by a factor of a thousand, to about 1.3 trillion, and the same code takes many minutes. The program did not change; the cubic term simply caught up.

The standard fix is not a faster slice but a different algorithm: expand outward from each of the 2n - 1 centres, comparing characters by index, which is O(n squared) with O(1) extra space (the full walkthrough is in palindrome expansion). The lesson is that avoiding the copy and improving the algorithm are often the same move.

One more place string slices bite: using them as dictionary keys or set members. Hashing a string of length k is O(k), so seen.add(s[i:i+k]) over a whole string costs O(n * k) in both the copy and the hash. If k is 5 that is nothing; if k is n/2 you have written a quadratic algorithm. Rolling hashes exist to break exactly this cost, as the Rabin-Karp page explains.

How do the common ways of taking part of a sequence compare?

They differ in whether they copy, how much they copy, and what they let you do with the result. This table covers the options you will actually reach for in Python.

OperationTimeExtra spaceNotes
a[i]O(1)O(1)Pure lookup, no copy
a[i:j] on a listO(k)O(k)New list, shallow copy of k pointers
s[i:j] on a str or bytesO(k)O(k)Fast memcpy, still linear
a[::-1]O(n)O(n)Full reversed copy
(lo, hi) index pairO(1)O(1)You carry the bounds yourself
memoryview(b)[i:j]O(1)O(1)Zero-copy view, bytes-like objects only
itertools.islice(a, i, j)O(j) to consumeO(1)Lazy, but must walk past the first i items
NumPy arr[i:j]O(1)O(1)A view onto the same buffer; writes show through

The row that surprises people is islice. It avoids building a list, but an iterator cannot jump, so skipping to position i still costs O(i). It saves memory, not time.

How do you avoid copying when you slice?

Pass the bounds instead of the data. Instead of handing a function a smaller sequence, hand it the original sequence plus lo and hi, and let each step work inside that range. This turns the copy from O(k) into two integer assignments and costs nothing in readability once you are used to it.

For recursion, that means adding two parameters:

def search(a, target, lo=0, hi=None):
    if hi is None:
        hi = len(a)
    if lo >= hi:
        return False
    mid = (lo + hi) // 2
    if a[mid] == target:
        return True
    if a[mid] < target:
        return search(a, target, mid + 1, hi)
    return search(a, target, lo, mid)

This is the same recursion as the copying version with the same shape, but each call is O(1), so the total is O(log n). When you need to hand a sub-range to something that insists on a standalone object, the zero-copy options are memoryview for bytes-like data and NumPy views for numeric arrays. A memoryview over a bytes object gives you slices that share the buffer; there is no equivalent for str, so with text you carry indices.

Two-pointer and window techniques are really a discipline of never slicing: both ends are integers that move, and the data stays put. If a solution to a problem like search in a rotated sorted array reaches for a[mid:], rewrite it with bounds first. The two pointers topic is full of examples where the pointers are the entire trick.

Do not over-correct, though. A slice is fine when it happens once, at the top level, on input you are already going to read in full. Copying a 100,000 element list once to hand to a helper is a 0.1 millisecond decision, not an algorithmic one. I only get suspicious when a slice appears inside a loop, a recursion, or a function that is meant to be called many times.

Is slicing O(n) in other languages too?

It depends on what the language decided a slice is. In Python a slice is a new object. In several other languages it is a small descriptor pointing at existing memory, which is why this question does not have the same answer everywhere.

  • Go: a slice is a header (pointer, length, capacity) over the same array, so reslicing is O(1). The flip side is aliasing: writes through one slice are visible through another.
  • Rust: &a[i..j] borrows a range with no copy, checked by the borrow checker rather than by convention.
  • Java: String.substring copies since JDK 7u6. Before that it shared the backing array, which was fast but could keep a huge string alive because of one tiny substring.
  • C++: std::string::substr copies; std::string_view and std::span do not.
  • JavaScript: slice on arrays copies; string behaviour is up to the engine, which may share storage internally. Do not rely on it for complexity claims.

This matters for interviews that let you pick the language. A solution that is O(log n) in Go with reslicing becomes O(n) when transliterated to Python line by line. If you port code between languages, slices are the first thing to audit.

How should you talk about slicing in an interview?

Say the cost out loud and pick indices by default. My position is that silent slicing is the more damaging habit, more than slicing itself. Claiming "this is O(log n)" about a recursive function that copies half the list at each level is a wrong answer delivered confidently, and interviewers who know Python catch it quickly.

A good sentence is: "I'll pass lo and hi rather than slicing, because each slice would copy up to n/2 elements and make this linear." That one line shows you know the cost model, and it costs about five seconds. If you do slice for brevity, name the price: "this slice is O(k), so the whole thing is O(n log n), which is fine for the input sizes you gave me." Both are acceptable. Neither pretending the copy is free nor refusing to ever slice is the goal.

It also helps to reason in totals. Write down how many elements each call copies and sum the series, as in the 500,000 + 250,000 + ... example above. Counting is more convincing than asserting, and it keeps you honest about your own code.

Frequently asked questions

Is s[i:j] O(1) or O(j - i)?

It is O(j - i), the length of the result, for strings, lists, tuples and bytes. Python builds a new object and copies the elements into it. If you need O(1) sub-ranges, carry indices, or use a memoryview for bytes or a NumPy array view for numeric data.

Does slicing count toward space complexity?

Yes. A slice of k elements allocates O(k) extra memory, and if you slice inside recursion, the copies at different depths can be alive at the same moment. A recursive search that slices halves can briefly hold about n elements of copies, which breaks an O(log n) space claim that an index-based version would satisfy.

Is memoryview the fix for string slicing?

Not for str, since memoryview only works with bytes-like objects. For text, pass start and end indices and compare characters in place. If you really are working with raw bytes, a memoryview slice is O(1) and shares the underlying buffer.

If you want a problem where this matters in practice, try longest substring without repeating characters: write it once with s[i:j] inside a loop, once with two indices, and compare how each one scales when the string grows from 1,000 to 100,000 characters.