Python List Slicing

Python list slicing is a technique that allows you to extract a subset of elements from a list by specifying a range of indices. The syntax for slicing is list[start:end:step], where:

start: The index where the slice begins (inclusive).

end: The index where the slice ends (exclusive).

step: (optional): The interval between each element in the slice.

Basic Slicing

list[start:end]: Extracts elements starting from the index start up to, but not including, the index end.

Example:


numbers = [0, 1, 2, 3, 4, 5, 6, 7]

# Extract elements from index 2 to 5 (excluding index 5)
subset = numbers[2:5]
print(subset)  # Output: [2, 3, 4]

Omitting start or end

Omitting start means the slice starts from the beginning.


my_list = [0, 1, 2, 3, 4, 5]
sliced = my_list[:3]  # Returns [0, 1, 2]

Omitting end means the slice goes till the end of the list


my_list = [0, 1, 2, 3, 4, 5]
sliced = my_list[2:]  # Returns [2, 3, 4, 5]

Using negative indices:

Negative indices start counting from the end of the list


my_list = [0, 1, 2, 3, 4, 5]
sliced = my_list[-3:]  # Returns [3, 4, 5]

Using step:

the step parameter determines the number of indices to skip between each selected element.

A positive step value (e.g., 2) skips that many indices forward.

Example: step=2 means every second element is taken.


my_list = [0, 1, 2, 3, 4, 5]
sliced = my_list[::2]  # Returns [0, 2, 4]

Example: step=3 means every third element is taken.


my_list = [0, 1, 2, 3, 4, 5]
sliced = my_list[::3]  # Returns [0, 1, 3, 4]

A negative step value (e.g., -1) skips indices in reverse

Example: step=-2 selects every second element in reverse order.


my_list = [0, 1, 2, 3, 4, 5]
sliced = my_list[::-2]  # Returns [5, 3, 1]

Example: step=-3 means every third element is taken in reverse order.


my_list = [0, 1, 2, 3, 4, 5]
sliced = my_list[::-3]  # Returns [5, 4, 2, 1]

Python List Slicing – Questions and Answers

Q 1: What is list slicing?

Ans: List slicing extracts a portion of a list using indices.

Q 2: How do you slice a list?

Ans: Using the syntax list[start:end].

Q 3: Does slicing modify the original list?

Ans: No, slicing returns a new list without changing the original.

Q 4: Can you skip elements while slicing?

Ans: Yes, using a step: list[start:end:step].

Q 5: Can negative indices be used in slicing?

Ans: Yes, negative indices count from the end of the list.

Python List Slicing – Objective Questions (MCQs)

Q1. What will be the output of the following code?

numbers = [10, 20, 30, 40, 50]
print(numbers[1:4]) 






Q2. What does the slice list[::-1] do?






Q3. What will be the output of the following code?

mylist = [1, 2, 3, 4, 5, 6]
print(mylist[:3]) 






Q4. What will mylist[2:] return if mylist = [10, 20, 30, 40, 50]?






Q5. Which of the following slice expressions returns every second element of a list nums?






Related Python List Slicing Topics