Transform each value in a list the same way

Viewed 50

I have a list of numbers, and I want to have a list with exactly those numbers within apostrophes (['a', 'b', 'c']). I have no idea what the syntax should be, but my guess was this

list = [1, 2, 3]
for i in list:
    list[i] = f"'{list[i]}'"
4 Answers

Do you want the apostrophes to stay with the numbers? In otherwords is this not the behavior you're looking for?

>>> print('1', '2', '4', '5', '8')
1 2 4 5 8

If so, then stick with the approach you started with (the other answers all just convert your numbers to strings). If you want your numbers to be displayed with their apostrophes then do

>>> x = [1, 2, 3]
>>> for i in range(len(x)):
>>>    x[i] = f"'{i}'"
>>>
>>> print(*x)
'0' '1' '2'

Use this code:

lists = [1, 2, 3]
for i in range(0, len(lists)):
    lists[i] = f'{lists[i]}'
print(lists)

another simplest option:

lists[i] = str(lists[i])
l1 = [1, 2, 3]
l2 = [str(i) for i in l1]

List comprehension is your friend when you want to do something with every element of the list.

>>> a = [1,2,4,5,8]
>>> b = [str(x) for x in a]
>>> b
['1', '2', '4', '5', '8']

Related