Python: Insert an element before each element of a list
Python List: Exercise - 47 with Solution
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.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/python-exercises/list/python-data-type-list-exercise-47.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics