smartyfy.mrindigi.com

Python Master Course V2 — 032. List Indexing and Slicing

SMARTYFY ACADEMY · MODULE 04 · Collections and Data Modelling · LESSON 032 / 200

List Indexing and Slicing

Study time: 70–100 minutes · Prerequisite: Lesson 031 and earlier Python collections lessons.

Video lesson

Video not yet available. Reserved area for a verified video link or embedded player. No video has been uploaded.

Learning outcomes

  • Understand the core concepts of list indexing and slicing.
  • Predict outputs and explain data changes.
  • Choose appropriate data structures and validate inputs.
  • Apply the lesson to a practical Python project.
  • Identify common mistakes and test edge cases.

Understand the idea, then trace the code

Positions select an item; slices select a sequence

A five-item list has indexes 0 through 4. Negative indexes count from the end: -1 is last and -5 is first. Both address existing slots. Indexing requests one item that must exist; check emptiness before asking for the first or last item.

A slice items[start:stop:step] includes start and excludes stop. A positive step moves toward larger indexes. Omitted start begins at the front, omitted stop continues to the end, and omitted step is one. The half-open convention helps calculate adjacent chunks and page sizes.

letters = ["A", "B", "C", "D", "E"]
print(letters[0], letters[-1])
print(letters[1:4])
print(letters[:3], letters[3:])
print(letters[::2])

Expected output:

A E
['B', 'C', 'D']
['A', 'B', 'C'] ['D', 'E']
['A', 'C', 'E']

Follow direction, not just endpoints

A negative step moves toward smaller indexes. letters[4:0:-2] visits indexes 4 and 2, producing E and C. letters[::-1] creates a reversed list. Defaults depend on direction: an omitted negative-step stop differs from explicit -1. Zero step raises ValueError; endpoints pointing against the step yield an empty slice.

Bounds and copying give different guarantees

An invalid single index raises IndexError. Slices clip endpoints: a page beyond the end is empty. Every slice creates a new outer list; replacing its slot leaves the source slot unchanged, but nested objects remain shared. Slicing is a shallow copy.

Replacement can change length

Reading a slice leaves the source unchanged; assigning to it mutates the list. A step-one replacement can have a different number of items, shifting the remainder. Extended slice assignment must supply exactly as many replacement items as selected positions. Aliases see the mutation.

tasks = ["draft", "review", "send", "archive"]
tasks[1:3] = ["approve"]
print(tasks)

Expected output:

['draft', 'approve', 'archive']

Build predictable pages

Define start as a nonnegative zero-based integer offset and size as a positive integer. Reject booleans. Short final pages and empty beyond-end pages are normal results; invalid requests are errors. The project below uses this explicit contract.

Progressive runnable example

Setup: Python 3.10 or newer, standard library only. Save as lesson_032.py and run with python lesson_032.py or python3. The outputs below are expected, not claims of execution on the website.

items=["A","B","C","D"]
print(items[0],items[-1])
print(items[1:3])

Expected output:

A D
['B', 'C']

Walkthrough: Read the starting values, identify each operation’s effect, and explain the resulting collection or return value. Change one input and predict the output before running the code again.

Project: predictable list pagination

Accept a list, a nonnegative integer start, and a positive integer size. Boolean arguments are excluded. The function returns a new outer list and leaves the original slots unchanged.

def page(items, start, size):
    if type(start) is not int or type(size) is not int:
        raise ValueError("start and size must be integers")
    if start < 0 or size <= 0:
        raise ValueError("start must be nonnegative; size must be positive")
    return items[start:start + size]

print(page(list(range(10)), 3, 4))
print(page([10, 20, 30, 40, 50], 3, 3))
print(page([10, 20, 30, 40, 50], 5, 3))

# Silent acceptance checks preserve the displayed sample output.
items = [1, 2, 3]
assert page(items, 2, 2) == [3]
assert page(items, 3, 2) == []
assert page([], 0, 2) == []
assert items == [1, 2, 3]
for start, size in [(0, 0), (True, 2), (-1, 2), (0, -1), (0.5, 2), (0, True), (0, 2.5)]:
    try:
        page(items, start, size)
    except ValueError:
        pass
    else:
        raise AssertionError("Invalid page request was accepted")

Expected output:

[3, 4, 5, 6]
[40, 50]
[]

The first sample preserves the original page example. The next two show a short final page and a beyond-end page together. Silent assertions test empty data, unchanged input, and invalid argument types/signs.

Optional later extension: read paginated records from CSV after file handling is taught. The slicing calculation can be verified before adding file input.

Common mistakes and professional practices

  • Assuming a nonempty collection without checking.
  • Accidentally mutating a shared list or nested object.
  • Confusing a method’s return value with its in-place effect.
  • Ignoring stable ordering or tie-breaking requirements.
  • Failing to validate data types and record fields.
  • Testing only the happy path rather than boundaries and failures.

Practice: predict, debug, and explain

Try each challenge before revealing its answer.

1. Trace three slices

a = [0, 1, 2, 3, 4, 5]
print(a[1:5:2])
print(a[5:1:-2])
print(a[-3:])

Predict all three lists and explain the excluded stop.

Optional hint

List visited indexes, stopping before the endpoint.

Reveal answer and reasoning

Expected output:

[1, 3]
[5, 3]
[3, 4, 5]

The visits are 1,3; 5,3; then the last three slots. Stop is excluded in both directions.

2. Predict replacement

a = [10, 20, 30, 40]
a[1:3] = [99]
print(a)

How many original items are replaced?

Optional hint

Compare the selected two slots with the replacement length.

Reveal answer and reasoning

Expected output:

[10, 99, 40]

Two items are replaced by one, shrinking length to three. a[1] = [99] would instead store a nested list in one slot.

3. Diagnose an index failure

For items = [2, 4], why does changing items[10] to items[10:] change the behavior?

Optional hint

An index demands one item; a slice can select none.

Reveal answer and reasoning

The index demands an eleventh item and raises IndexError. The slice requests the available group from that offset and returns []. Their return types and guarantees differ.

4. Find a shared object

original = [[1], [2]]
copy = original[:]
copy[0].append(9)
copy[1] = [7]
print(original)
print(copy)

Which update crosses the copy boundary?

Optional hint

The outer list was copied; the inner lists were shared.

Reveal answer and reasoning

Expected output:

[[1, 9], [2]]
[[1, 9], [7]]

The first inner list is shared, so append appears through both lists. Replacing slot 1 affects only the copied outer list.

5. Specify pagination boundaries

For items = [1, 2, 3], what do page calls with (2,2), (3,2), (0,0), and (True,2) do?

Optional hint

Separate valid end-of-data from invalid argument types or sizes.

Reveal answer and reasoning

The first returns [3], the second []. Zero size and Boolean start raise ValueError. Ordinary end-of-data differs from an invalid request.

Mastery checkpoint

Explain the data structure and operation, run the example, adapt the project and demonstrate at least three edge-case tests. Review the prerequisite lesson if you cannot predict the result.

Summary: List Indexing and Slicing becomes reliable when paired with clear data models, validation and repeatable testing.

Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.