How to add characters to a specific element in a list without overwriting the entire list?

Question:

Okay, so my original problem was adding characters to a specific element in a list, but then I encountered the problem of my fix overwriting my entire list, leaving me with the edited element.

My code

listy = ['item_1','item_2','item_3']

listy = ['('+listy[1]+')']

print(listy)
>'(item_2)'

I understand why this is happening, I just don’t know how to also add back the rest of the list (non-manually)

I tried doing:

listy = [listy[0:1] + '('+listy[1]+')' + listy[2:]]

And got back a TypeError, which I expected, but wanted to make sure it didn’t work first.

This was all I tried.

Asked By: Connor

||

Answers:

Assign to the list index, not the variable holding the entire list.

listy[1] = '('+listy[1]+')'
Answered By: Barmar

if you got your problem correctly, you want to update listy[1] with the new variable you want.

you can do it easy by assign it to the index like that

listy = ['item_1','item_2','item_3']
listy[1] = f"({listy[1]})"
print(listy)

the output will be :

['item_1', '(item_2)', 'item_3']
Answered By: Osama Elsherif
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.