# Lists & Slicing

> Master Python dynamic arrays, zero-based and negative indexing, the mechanics of slice copies, and the crucial distinction between shallow and deep copies.

Subject: Python | Lesson 5 of 24 | 7 min read
Interactive lesson: https://codewithanimation.in/python/lists
Previous: [For & While Loops](https://codewithanimation.in/python/loops.md) | Next: [Tuples & Sequence Unpacking](https://codewithanimation.in/python/tuples.md)

## Dynamic Arrays of Object Pointers

In Python, a list is an ordered, mutable sequence of arbitrary objects. Under the hood in CPython, a list is implemented as a dynamic array of pointers (`PyObject*`), not a linked list.

Because the pointers are stored contiguously in memory, accessing any element by its numeric index with `items[i]` is a lightning-fast O(1) constant-time operation.

Lists can store mixed data types simultaneously, including integers, strings, floats, and even other nested lists.

## Dual-Direction Indexing & Slice Notation

Python provides dual indexing for every sequence. Positive indices count forward from left to right starting at `0`. Negative indices count backward from right to left starting at `-1` (where `-1` always references the final element).

Slice notation `sequence[start:stop:step]` extracts a subsequence. The `start` index is inclusive, but the `stop` index is exclusive: `items[1:4]` extracts indices 1, 2, and 3.

Omitting indices falls back to sensible defaults: `start` defaults to `0`, `stop` defaults to `len(items)`, and `step` defaults to `1`.

## Slicing Tricks and Common Methods

A negative step reverses the iteration direction: `items[::-1]` returns a reversed copy of the entire list in a single memory-efficient C-level operation.

Adding elements: `items.append(x)` adds an element to the end in amortized O(1) time. `items.extend(iterable)` unpacks and appends each element from another iterable.

Removing elements: `items.pop()` removes and returns the last element in O(1) time. In contrast, `items.pop(0)` or `items.insert(0, x)` requires shifting every remaining pointer in memory, costing O(n) linear time.

## Common mistake: The Shallow Copy Gotcha

Slicing a list with `b = a[:]` or calling `b = a.copy()` creates a new outer list array, but it only copies the object references (a shallow copy).

If the list contains immutable values like numbers or strings, this copy is completely independent. However, if the list contains nested mutable structures like child lists or dictionaries, both `a` and `b` still point to the exact same child objects.

Modifying a nested sub-list via `b[0].append(99)` alters `a[0]` as well. When full independence is required for nested structures, use `copy.deepcopy()` from Python's standard library.

## Tip: Use collections.deque for FIFO Queues

Never use a standard Python list as a First-In-First-Out (FIFO) queue with `list.pop(0)`. Popping from the front forces all remaining elements to shift over in memory (O(n)). Instead, import `collections.deque`, which provides O(1) pops and appends from both ends.

## Try it: The Slicing & Memory Inspector

Test different slicing expressions on an array. Watch how positive and negative indices align, and inspect the resulting shallow-copied subarray in memory.

The animation is on the lesson page and is not part of this text version: https://codewithanimation.in/python/lists

## Check yourself

### Question 1

Given `nums = [10, 20, 30, 40, 50]`, what does `nums[1:4]` evaluate to?

- A. [20, 30, 40]
- B. [20, 30, 40, 50]
- C. [10, 20, 30]
- D. [10, 20, 30, 40]

Correct answer: A

Slicing uses half-open intervals [start, stop). `nums[1:4]` includes indices 1, 2, and 3 (values 20, 30, and 40), excluding index 4.

- Why not B: In Python slicing, the stop index is strictly exclusive. Index 4 (value 50) is omitted.
- Why not C: Python uses 0-based indexing. Index 1 corresponds to value 20, not 10.
- Why not D: Index 0 is 10, but start index 1 begins the slice at 20.

### Question 2

What is the time complexity of removing the first element of a Python list using `my_list.pop(0)`?

- A. O(n) linear time, because all subsequent element pointers must shift left in memory.
- B. O(1) constant time, because Python lists are doubly linked lists.
- C. O(log n) logarithmic time.
- D. O(n^2) quadratic time.

Correct answer: A

CPython lists store pointer arrays in contiguous RAM. Removing index 0 forces all remaining n-1 elements to shift left by one slot, running in O(n) time.

- Why not B: Python lists are contiguous dynamic pointer arrays, not linked lists. Popping index 0 forces n-1 pointers to shift.
- Why not C: Array memory shifts require linear time proportional to the number of elements.
- Why not D: A single memory shift pass is linear O(n), not quadratic.

### Question 3

If `orig = [[1, 2], [3, 4]]` and `clone = orig[:]`, what happens if you run `clone[0].append(99)`?

- A. Both orig[0] and clone[0] become [1, 2, 99], because slice copying creates a shallow copy sharing nested objects.
- B. Only clone[0] is modified, because slicing performs a recursive deep copy.
- C. Python raises a TypeError because nested lists cannot be sliced.
- D. Python creates a tuple automatically.

Correct answer: A

Slicing performs a shallow copy. The outer lists are separate, but their elements point to the exact same inner lists in heap memory. Use `copy.deepcopy()` to clone recursively.

- Why not B: Slicing only duplicates the outer pointer array. The nested sub-lists remain shared.
- Why not C: Slicing nested lists is completely valid Python syntax.
- Why not D: Slicing a list produces a new list, never a tuple.

## Remember this

- Python lists are contiguous dynamic pointer arrays, offering O(1) random access indexing.
- Positive indices count from 0 (left to right); negative indices count from -1 (right to left).
- Slicing [start:stop:step] is half-open: start is inclusive, stop is strictly exclusive.
- Slicing creates a shallow copy: outer arrays differ, but nested mutable objects remain shared.
- Avoid pop(0) on large lists; use collections.deque for O(1) FIFO queues.
