Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Insert the string at the beginning of all items in a list in Python
In this tutorial, we'll learn how to insert a string at the beginning of all items in a list in Python. For example, if we have a string "Tutorials_Point" and a list containing elements like "1", "2", "3", we need to add "Tutorials_Point" in front of each element to get "Tutorials_Point1", "Tutorials_Point2", "Tutorials_Point3".
Using List Comprehension with format()
The most straightforward approach is using list comprehension with string formatting ?
sample_list = [1, 2, 3]
result = ['Tutorials_Point{0}'.format(i) for i in sample_list]
print(result)
['Tutorials_Point1', 'Tutorials_Point2', 'Tutorials_Point3']
Using map() with format()
We can also use the map() function to apply string formatting to all elements ?
sample_list = [1, 2, 3]
sample_str = 'Tutorials_Point'
sample_str += '{0}'
result = list(map(sample_str.format, sample_list))
print(result)
['Tutorials_Point1', 'Tutorials_Point2', 'Tutorials_Point3']
Using f-string (Python 3.6+)
For modern Python versions, f-strings provide a cleaner syntax ?
sample_list = [1, 2, 3]
prefix = 'Tutorials_Point'
result = [f'{prefix}{i}' for i in sample_list]
print(result)
['Tutorials_Point1', 'Tutorials_Point2', 'Tutorials_Point3']
Using String Concatenation
Simple string concatenation also works effectively ?
sample_list = [1, 2, 3] prefix = 'Tutorials_Point' result = [prefix + str(i) for i in sample_list] print(result)
['Tutorials_Point1', 'Tutorials_Point2', 'Tutorials_Point3']
Comparison
| Method | Readability | Performance | Python Version |
|---|---|---|---|
| List Comprehension + format() | Good | Medium | All versions |
| map() + format() | Medium | Good | All versions |
| f-string | Excellent | Best | 3.6+ |
| String Concatenation | Excellent | Good | All versions |
Conclusion
Use f-strings for modern Python applications due to their excellent readability and performance. For older Python versions, string concatenation with list comprehension provides a clean and efficient solution.
