Member Avatar for Rebecca_2

I apologise if there are answers to this elsewhere but my programming is very basic and I don't really understand - so please keep it simple and please be patient.

If I have a list of strings. Is there an easy way of creating variables called by the items in the list?

i.e.

list1 = ['A', 'B', 'C', 'D', ... 'X', 'Y', 'Z']
A = 
B = 
C =
.
.
.
Z = 

A prod in the right direction would be appreciated!

The answer is yes it is possible to create global variables this way, but it is considered poor programming. Here is this forbidden fruit

globals().update((name, 'foo') for name in list1)

Now all the variables exist, with value the string "foo".

Apart from this bad way to do it there are several good alternatives. The first one is to use a dictionary:

val = dict((name, 'foo') for name in list1)

Then val["A"] has value 'foo'. Another way is to use a class

class val:
    pass

for name in list1: setattr(val, name, 'foo')

Then val.A is 'foo' etc.

One can also use a class instance, often I use

class Static(object):
    def __init__(self, *args, **kwd):
        self.__dict__.update(*args, **kwd)

val = Static((name, 'foo') for name in list1)

val.A = 'bar'
print(val.A)

Edit: bugfix for class Static.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.