How to Use List Slices for Insertion and Deletion in Python

1. Introduction

Python's list slicing is a versatile feature that not only allows for accessing parts of lists but also for inserting and deleting elements in a concise manner. Utilizing slices for insertion and deletion can make the code more readable and Pythonic, compared to using methods like insert(), append(), or del.

Definition

List slicing in Python refers to accessing a specific range or subset of a list's elements. This feature can also be used to insert new elements into a list by assigning a slice to a sequence of elements. Similarly, deleting elements using slices involves assigning an empty list to a slice of a list.

2. Program Steps

1. Create an original list of elements.

2. Insert elements into the list using slicing.

3. Delete elements from the list using slicing.

4. Print the list after each operation to observe the changes.

3. Code Program

# Step 1: Create an original list
original_list = [1, 2, 4, 5]

# Step 2: Insert an element using slicing
# We want to insert the number 3 between 2 and 4
original_list[2:2] = [3]  # Insert at index 2

# Step 3: Print the list after insertion
print("After insertion:", original_list)

# Step 4: Delete elements using slicing
# We want to delete the number 3 that we just inserted
original_list[2:3] = []  # Delete the element at index 2

# Step 5: Print the list after deletion
print("After deletion:", original_list)

Output:

After insertion: [1, 2, 3, 4, 5]
After deletion: [1, 2, 4, 5]

Explanation:

1. original_list is initialized with the values [1, 2, 4, 5].

2. To insert the number 3, a slice from index 2 to index 2 is assigned the list [3], which does not remove any elements but adds 3 at the specified index.

3. After the insertion, the print statement displays the list as [1, 2, 3, 4, 5].

4. To delete the number 3, a slice from index 2 to index 3 is assigned an empty list [], effectively removing the element at index 2.

5. The final print statement shows the list reverted to its original form [1, 2, 4, 5].

6. Throughout the operations, original_list is modified in place, demonstrating how slices can be used for both insertion and deletion.

Comments