Python Practice › List Programs › Program 75

Insert an element before each item

EasyList Programs · 75 of 100

Write a Python program to insert an element before each element of a list.

Advertisement
Input
[3, 5, 7, 8], element "a"
Output
['a', 3, 'a', 5, 'a', 7, 'a', 8]

Approach

  1. A nested comprehension produces the pair for each item.

Solution

Python
items = [3, 5, 7, 8]print([x for item in items for x in ("a", item)])
Output
['a', 3, 'a', 5, 'a', 7, 'a', 8]

Learn the concept

New to this topic? Read the lesson, then come back.

More list programs

← All 100 List Programs

Leave a Comment