1

I am trying to do the following in python: I have a list which contains some string values. The list looks like this:

       parameters =  ['RH', 'WindSp_Avg', 'WindDir']

What I want to do - and I really hope the question is not ridiculous - is to create three lists which each of them have the name of the "parameters" list. For example:

         RH = []
         WindSp_Avg = []
         WindDir = []

I am new in python and although I had searched a bit online I couldn't find some elegant way to do something like this.

I am trying something like this:

    for i in parameters:

        parameters[0] = []

But it doesn't seem to work. Any suggestions?

Thanks Dimitris

1
  • In Python they're called list, arrays are something different. Commented Apr 5, 2013 at 9:54

4 Answers 4

9

What you are trying to do is very unsafe and is against all good practices. Is there a problem in simply creating a dictionary?

myVars = {}
for param in parameters:
    myVars[param] = []

WARNING The following code is for educational purposes! DO NOT USE IT IN REAL CODE!

You can do a hard hack to add dynamically a variable to the local variables inside a function. Normally locals() represent all local variables. However simply adding to that dictionary won't solve the problem. There is a hack to force Python to reevaluate locals by using exec, for example:

def test():
    for param im parameters:
        locals()[param] = []
    exec ""
    print WindSp_Avg

and result:

>>> test()
[]
Sign up to request clarification or add additional context in comments.

1 Comment

hope to see an answer which exactly answer his question
1
parameters = ['RH', 'WindSp_Avg', 'WindDir']
for i in parameters:
    vars()[i] = [];
print locals()

Comments

0

To create a variable you can do so:

parameters =  ['RH', 'WindSp_Avg', 'WindDir']
for i in parameters:
    exec("%s = []" % i);

print vars()

Comments

0

you could something like this:

code = "{0} = []"
for i in parameters:
    codeobj = compile(code.format(i), "/dev/null", "single")
    eval(codeobj)

but i think tha's very unsafe. Because it could be something in parameters and that will be excuted by the eval. So please only use this if it's only really necessary and security is less important.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.