w3resource

Python: Insert a given string at the beginning of all items in a list

Python List: Exercise - 63 with Solution

Write a Python program to insert a given string at the beginning of all items in a list.

Python: Insert a given string at the beginning of all items in a list

Sample Solution:

Python Code:

# Define a list 'num' containing integers
num = [1, 2, 3, 4]

# Use a list comprehension to create a new list of strings, where each string is formed by appending the index (formatted as a string) to the string 'emp'
# This effectively generates a list of strings with elements like 'emp1', 'emp2', 'emp3', 'emp4'
new_list = ['emp{0}'.format(i) for i in num]

# Print the new list 'new_list' containing the formatted strings
print(new_list)

Sample Output:

['emp1', 'emp2', 'emp3', 'emp4']

Flowchart:

Flowchart: Insert a given string at the beginning of all items in a list

Python Code Editor:

Previous: Write a Python program to print a list of space-separated elements.
Next: Write a Python program to iterate over two lists simultaneously.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

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-63.php