This tutorial will discuss how to remove elements by index range in a Python list.
Suppose we have a list of numbers, like this,
sampleList = [12, 13, 14, 15, 16, 17, 18, 19, 20, 21]
Now, we wish to remove elements based on a specific index range. For instance, we might want to remove elements from index 3 to index 6. To achieve this, we can utilize list slicing. We’ve crafted a dedicated function for this purpose.
def removeByIndexRange(listObj, startIndex, endIndex): # Using slicing to exclude the range of indices return listObj[:startIndex] + listObj[endIndex+1:]
This function accepts three arguments: the list itself, the starting index, and the ending index. The function extracts elements from the beginning of the list up to the starting index and then from the ending index to the list’s conclusion. These segments are then concatenated to form a new list, effectively removing the specified range of elements.
Let’s see the complete example,
def removeByIndexRange(listObj, startIndex, endIndex): # Using slicing to exclude the range of indices return listObj[:startIndex] + listObj[endIndex+1:] # A List of Integers sampleList = [12, 13, 14, 15, 16, 17, 18, 19, 20, 21] print("Original List:", sampleList) startIndex = 3 endIndex = 6 # Remove elements in list from index range 3 to 6 sampleList = removeByIndexRange(sampleList, startIndex, endIndex) print(f"List after removing elements from index {startIndex} to {endIndex}:") print(sampleList)
Output
Original List: [12, 13, 14, 15, 16, 17, 18, 19, 20, 21] List after removing elements from index 3 to 6: [12, 13, 14, 19, 20, 21]
Summary
Frequently Asked:
Today, we learned how to remove elements by index range in a Python list.