0

I've used locals() function and created some variables. Now I need to fetch all the variables created into a list, how should I do?

example:

column_list=[x for x in range(100)]

for i,j in enumerate(column_list):
    locals()['v'+str(i)]=pd.DataFrame(['Y','N'],columns=[j])

Now, I have variables, v0 ~ v99, each of which is an independent data frame.

I need to fetch all the variables into a variable_list

So I can use for loop on all the variables:

variable_list -> [v0,v1,v2,v3,v4.v5.......]
S.Gu
  • 637
  • 1
  • 6
  • 15

1 Answers1

1

Level up the abstraction. Writing to locals() is not reliable, and is advised against in the documentation.

You should change the code where it creates sequential local variables named v0, v1, ... v99 so that appends into one list named v in the first place.

Now, your "variable_list" is just v itself and the values in the list are accessible v[0], v[1], ... v[99].

wim
  • 338,267
  • 99
  • 616
  • 750
  • Yea, that worked.. But I still interested in knowing how to fetch existing variables anyway – S.Gu Aug 06 '18 at 02:58