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!
Advertisement
Answer
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']