Skip to Content

Python Basics: How Does Python List Slicing Work with a Start and Stop Index?

What Do You Get When You Slice a Python List Like lst[1:3]?

Learn how Python’s list slicing extracts a sublist using the [start:stop] syntax. Understand that the start index is inclusive and the stop index is exclusive, which is crucial for correctly selecting a range of elements from a list.

Question

Given lst = [10, 20, 30, 40], what does lst[1:3] evaluate to?

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

Answer

C. [20, 30]

Explanation

Elements at indices 1 and 2.

The expression lst[1:3] evaluates to [20][30].

This operation is known as list slicing, and it creates a new list containing a subset of the original list’s elements. The syntax for slicing is list[start:stop].

  • The start index is the position of the first element to be included in the slice. It is inclusive. In this case, the start index is 1. The element at index 1 in lst is 20.
  • The stop index is the position of the first element that should not be included in the slice. It is exclusive. In this case, the stop index is 3. The slice will contain elements up to, but not including, the element at index 3.

Applying this to lst = [10][20][30][40]:

  • The slice starts at index 1 (the value 20).
  • It includes the element at index 2 (the value 30).
  • It stops before reaching index 3 (the value 40).

Therefore, the resulting slice is [20][30].

The other options are incorrect slices:

  • [10][20][30] would be the result of lst[0:3].
  • [20][30][40] would be the result of lst[1:4] or lst[1:].
  • [30][40] would be the result of lst[2:4] or lst[2:].

Python Basics: Learn, Apply & Build Programs certification exam assessment practice question and answer (Q&A) dump including multiple choice questions (MCQ) and objective type questions, with detail explanation and reference available free, helpful to pass the Python Basics: Learn, Apply & Build Programs exam and earn Python Basics: Learn, Apply & Build Programs certificate.