How to append a copy of each element of a list to itself?

Question:

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.

Asked By: Felix

||

Answers:

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']
Answered By: ThePyGuy
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.