Have done some searching through Stack Exchange answered questions but have been unable to find what I am looking for.
Given the following list:
a = [1, 2, 3, 4]
How would I create:
a = ['hello1', 'hello2', 'hello3', 'hello4']
Thanks!
We can use format() function which allows multiple substitutions and value formatting. Another approach is to use map() function. The function maps the beginning of all items in the list to the string.
To prepend to a list in Python, use the list. insert() method with index set to 0, which adds an element at the beginning of the list. The insert() is a built-in Python function that inserts an item to the list at the given index.
For a list, += is more like the extend method than like the append method. With a list to the left of the += operator, another list is needed to the right of the operator. All the items in the list to the right of the operator get added to the end of the list that is referenced to the left of the operator.
Use a list comprehension:
[f'hello{i}' for i in a]
A list comprehension lets you apply an expression to each element in a sequence. Here that expression is a formatted string literal, incorporating i
into a string starting with hello
.
Demo:
>>> a = [1,2,3,4]
>>> [f'hello{i}' for i in a]
['hello1', 'hello2', 'hello3', 'hello4']
One more option is to use built-in map function:
a = range(10)
map(lambda x: 'hello%i' % x, a)
Edit as per WolframH comment:
map('hello{0}'.format, a)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With