assigning values to array element

B

Ben

Hi all,

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?

Thanks
Ben
 
P

Peter Hansen

Ben said:
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
 
P

Paul Rubin

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?

Um, you probably really don't want to do that. See the docs about
how Python dictionaries work. Then try something like:

m = ['Peter', 'Sam', 'Dave', 'Carl']
table = {} # note these are curly braces
for o in m:
table[o] = 10
 
M

Michael Peuser

Ben said:
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?

I think 'old stuff' is really appropriate here:

for index in xrange(len(m)):
m[index]=10

Kindly
MichaelP
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,048
Latest member
verona

Latest Threads

Top