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.
Answers:
Assign to the list index, not the variable holding the entire list.
listy[1] = '('+listy[1]+')'
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']
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.
Assign to the list index, not the variable holding the entire list.
listy[1] = '('+listy[1]+')'
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']