-1
x=1
code(x)=5
print(code1)

I want this to work andit print "5" could anybody help me do this in python.

  • 2
    Your code doesn't make any sense. You didn't define a `code1` variable. What you're probably looking for is an array. – Robert Harvey Sep 20 '14 at 15:48
  • That is not valid syntax. You cannot assign to a function like that (if that's what `code` is). – Cory Kramer Sep 20 '14 at 15:49
  • 1
    Guys, clearly it is not valid syntax, and clearly that is why the OP is asking the question. They are looking for something like a `dict`, but don't know what it is called or how to use it, so they gave an example of something close to what they want to explain. – SethMMorton Sep 20 '14 at 15:58
  • While what you want to do is technically possible, it's really not something you should ever do. The only time it's valid to do that is if you can personally answer the question "why should I never do this?". – Bryan Oakley Sep 20 '14 at 16:10

4 Answers4

0

You can use "code" as a list.

x=1
code=[0,0]
code[x]=5
print(code[1])

or as a dict:

x=1
code={}
code[x]=5
print(code[1])

depends on how you will use "code".

Hrabal
  • 2,403
  • 2
  • 20
  • 30
0
 myList=[1,2,3,4,5,6]
 print myList[2]

will print 3. You can assign an index to a variable and do this:

 index=2
 print myList[index]

will print 3.

Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
0

As the other answer suggested, you'll better use dictionary or a list for this.

But for your question you could it like this:

x = 1
exec(('code' + x) + '=5')
print code1

code1 will be 5.

Tomzan
  • 2,808
  • 14
  • 25
-1
code=[0,0]

x=1
code[x]=5
print(code[1])
user3684792
  • 2,542
  • 2
  • 18
  • 23