Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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

listy[1] = '('+listy[1]+')'
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading