-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
  • 55,782
  • 14
  • 81
  • 108
  • > 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
  • 306
  • 1
  • 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,799
  • 1
  • 7
  • 20