Python: Insert an element before each element of a list
Insert Element Before Each List Item
Write a Python program to insert an element before each element of a list.
Sample Solution:
Python Code:
# Define a list 'color' containing color names
color = ['Red', 'Green', 'Black']
# Print the original list 'color'
print("Original List: ", color)
# Use a list comprehension to create a new list 'color' by inserting the letter 'c' before each element in the original list
# This results in each color name being duplicated with 'c' added in front of it
# Print the updated list 'color'
color = [v for elt in color for v in ('c', elt)]
print("Updated List: ", color)
Sample Output:
Original List: ['Red', 'Green', 'Black'] Updated List: ['c', 'Red', 'c', 'Green', 'c', 'Black']
Flowchart:
Python Code Editor:
Previous: Write a Python program to select the odd items of a list.
Next: Write a Python program to print a nested lists (each list on a new line) using the print() function.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics