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 append a copy of each element of a list to itself?

I have a list of variables like

list = ["$res", "$hp", "def"]

etc. I want to append each element of that list to itself at the start with a hyphen preferably so it looks like,

list = ["$res - $res", "$hp - $hp", "$def - $def"]

How do I achieve this in python? I already have a function takes a list of variable setting code lines and strips them of all text besides the variables themselves. Now I want to combine it with a function that does this to prepare a list of variable names and their values on demand. This is all for some other program but I wanted to do the processing in python.

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

>Solution :

You can use the formatted string for each values in the list to create the required values, you can achieve it using List-Comprehension:

>>> lst = ["$res", "$hp", "$def"]
>>> [f"{x} - {x}" for x in lst]

['$res - $res', '$hp - $hp', '$def - $def']
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