ReviseAlgo Logo

Lists

List Slicing

Accessing sublists with slicing

Interview: Very common in interviews — tests understanding of slice semantics and assignment

Last Updated: June 12, 2026 9 min read

Slicing extracts sublists using the syntax lst[start:stop:step]. It's one of Python's most powerful features — slices can read, replace, delete, and even resize lists. All slicing operations create new list objects (shallow copies).

Slice Syntax

  • lst[a:b]: Elements from index a to b-1 (b is exclusive)
  • lst[a:]: From index a to end
  • lst[:b]: From start to index b-1
  • lst[::step]: Every step-th element
  • lst[::-1]: Reverse the list (idiom)
  • Negative indices: Count from end: lst[-3:] → last 3 elements

Slice Assignment

  • Replace: lst[1:3] = [10, 20, 30] — can replace with different length
  • Insert: lst[2:2] = [99] — insert at index 2 (empty slice)
  • Delete: lst[1:3] = [] or del lst[1:3]
  • Extended slice: lst[::2] = [0, 0, 0] — must match exact length

Common Slice Patterns

  • Copy: copy = lst[:] — shallow copy
  • Head/tail: head, *tail = lst or head = lst[0]; tail = lst[1:]
  • Window: lst[i:i+window_size] — sliding window
  • Chunking: [lst[i:i+n] for i in range(0, len(lst), n)]

Interview Tip

Out-of-bounds slicing doesn't raise errors: [1,2,3][10:20] returns [] (empty list). This is different from out-of-bounds indexing which raises IndexError.

Use Cases

Extracting sublists for data processing

Implementing sliding window algorithms

List rotation and reversal in coding interviews

Chunking data for batch processing

Common Mistakes

Forgetting that stop index is exclusive: lst[0:3] gives indices 0,1,2 not 0,1,2,3

Using lst[:] thinking it is a deep copy — nested objects are still shared references

Extended slice assignment (lst[::2] = [...]) requires exact length match

Not knowing out-of-bounds slices return empty lists instead of raising errors