Python Practice › List Programs › Program 86
Insert a sublist at an index
Write a Python program to insert a sublist into a list at a given index.
Input
[4, 6, 8, 2, 3, 5], sublist [5, 2, 6], index 3
Output
[4, 6, 8, [5, 2, 6], 2, 3, 5] [4, 6, 8, 5, 2, 6, 2, 3, 5]
Approach
insertadds the sublist as one item; slice assignment adds its items.
Solution
items = [4, 6, 8, 2, 3, 5]nested = items.copy()nested.insert(3, [5, 2, 6])print(nested) flat = items.copy()flat[3:3] = [5, 2, 6]print(flat)Output
[4, 6, 8, [5, 2, 6], 2, 3, 5] [4, 6, 8, 5, 2, 6, 2, 3, 5]
Line by line
Line 3
The sublist becomes one element.
Line 7
Assigning to the empty slice [3:3] splices the items in.
Learn the concept
New to this topic? Read the lesson, then come back.