Python Practice › List Programs › Program 86

Insert a sublist at an index

EasyList Programs · 86 of 100

Write a Python program to insert a sublist into a list at a given index.

Advertisement
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

  1. insert adds the sublist as one item; slice assignment adds its items.

Solution

Python
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.

More list programs

← All 100 List Programs

Leave a Comment