Home > Blockchain >  How to append a copy of each element of a list to itself?
How to append a copy of each element of a list to itself?

Time:09-16

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.

CodePudding user response:

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']
  • Related