Python Practice › List Programs › Program 75
Insert an element before each item
Write a Python program to insert an element before each element of a list.
Input
[3, 5, 7, 8], element "a"
Output
['a', 3, 'a', 5, 'a', 7, 'a', 8]
Approach
- A nested comprehension produces the pair for each item.
Solution
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.