assigning values to array element

Peter Hansen peter at engcorp.com
Tue Oct 14 22:36:34 EDT 2003


Ben wrote:
> 
> This may sound easy but I'm having trouble assigning values to array
> element. My problem is as follows:
> 
> m = ['Peter', 'Sam', 'Dave', 'Carl']
> for o in m:
>   # Here first o is 'Peter'.. I want to do something like this:
>   Peter = 10
> 
>   # if i do %s %o = 10, it gives me error...
> 
> How can I do it?

You seem to want to create variables with names Peter, Sam, etc.

If that's so, you should explain your problem in more detail,
because doing this dynamically is useless: after all, how do
you plan to *retrieve* those variables if you don't know in
advance what they are called?

What you are trying to do is probably better accomplished using
Python dictionary type:

# using your "m" list of names, above:
d = {}
for name in m:
    d[name] = 10

# then to access things, do this:
print d['Peter']

If you need more, please explain the rationale behind the program, 
rather than just examples of code that didn't work, so we'll 
understand *why* you are trying to do what you are trying to do.

-Peter




More information about the Python-list mailing list