List comprehension using f-strings

Question:

I have three variables

a = 1
b = 2
c = 3

and I want to have a string like 'a=1, b=2, c=3'

so, I use f-string,

x = ''
for i in [a, b, c]:
   x += f"{i=}"

but it gives,

x
'i=1, i=2, i=3, '

how do I make the i to be a, b, and c?

Asked By: apostofes

||

Answers:

A list doesn’t remember the names of variables assigned to it. For that, you need a dictionary.

x = ""
my_dict = {'a': a, 'b': b, 'c': c}
for k, v in my_dict.items():
    x += f"{k}={v}, "
Answered By: Silvio Mayolo

The list [a, b, c] is indistiguishable from the list [1, 2, 3] — the variables themselves are not placed in the list, their values are, so there is no way to get the variable names out of the list after you’ve created it.

If you want the strings a, b, c, you need to iterate over those strings, not the results of evaluating those variables:

>>> ', '.join(f"i={i}" for i in "abc")
'i=a, i=b, i=c'

If you want to get the values held by the variables with those names, you can do this by looking them up in the globals() dict:

>>> a, b, c = 1, 2, 3
>>> ', '.join(f"{var}={globals()[var]}" for var in "abc")
'a=1, b=2, c=3'

but code that involves looking things up in globals() is going to be really annoying to debug the first time something goes wrong with it. Any time you have a collection of named values that you want to iterate over, it’s better to just put those values in their own dict instead of making them individual variables:

>>> d = dict(a=1, b=2, c=3)
>>> ', '.join(f"{var}={val}" for var, val in d.items())
'a=1, b=2, c=3'
Answered By: Samwise

Using gloabls is not always a good idea if you want a solution that aovid using them you can inspect the variables that are declare using inspect module, there is thread regarding the getting the name of varibles here, from were the I took the function.

import inspect

def retrieve_var(var):
    callers_local_vars = inspect.currentframe().f_back.f_locals.items()
    return [var_name for var_name, var_val in callers_local_vars if var_val is var]

and now you can use a loop as similar to that you where using

a, b, c = 1, 2, 3

x = ''

for i in [a, b, c]:
    var = retrieve_var(i)
    x += f"{var[0]}={i}, "
Answered By: Lucas M. Uriarte