-1

Say I have a list:

questions = ['a','b','c','d','e']

And I want to make a variable named after an element in this list:

questions[2] = 'Hello world'

This is the way I thought I could do it but when I try to print it:

print(b)

I get this error:

NameError: name 'b' is not defined

Obviously, python has made an entirely new variable called 'questions[2]'. How can I get python to recognize questions[2] as 'b' and not the 'questions[2]'?

khelwood
  • 52,115
  • 13
  • 74
  • 94
Chris
  • 23
  • 3
  • > python has made an entirely new variable called 'questions[2]', will no, it will assign the cell at index `2` (previously holding value `'c'`) the new value `'Hello world'`. Note: list Indexing starts at 0 not 1. – adnanmuttaleb Mar 01 '20 at 07:30

2 Answers2

0

Do you know the difference between b and 'b'? You are missing between variable's name and value.

Thien Tran
  • 161
  • 10
0

While it's possible, there really shouldn't be any reason to do this. But anyways you can use exec().

questions = ['a','b','c','d','e']
exec(questions[1] + ' = "Hello world"')
print(b)

Note that using exec() is generally discouraged. Perhaps a dictionary would suit your needs instead.

alec
  • 5,381
  • 1
  • 6
  • 20
  • I don't understand what the exec() is doing, could you elaborate on what is going on? – Chris Mar 01 '20 at 07:52
  • It executes the string as if it were a python statement, thus assigning `"Hello world"` to the variable `b` . – alec Mar 01 '20 at 07:55