-2

How can I use a variable name as the name of a list? The first print statement gives a 1, that's correct, but the last line gives a character m because it is the first char of the string my_list.
Instead, I want the first item from my_list.

my_list = [1, 2, 3]
word = "my_list"
print(my_list[0])  # 1
print(word[0])  # "m"
maciejwww
  • 1,067
  • 1
  • 13
  • 26
Dick Stada
  • 25
  • 1

1 Answers1

2

This is poor practice. Do not name variables using strings.

A better idea is to use a dictionary to store your value, utilizing a string key for your identifier.

For example:

my_list = [1,2,3]

d = {'word': my_list}

Then access via d['word'].

jpp
  • 159,742
  • 34
  • 281
  • 339
  • This was the plan: I had a couple of lists with names like men1, men2 , men3, etc. and wanted to get the right list, dependable on some input. So "men" + var. Now, I realise that I'd better make one nested list. Thanks all. – Dick Stada May 14 '18 at 14:29
  • @DickStada, You can still implement your plan. Just use a dictionary. – jpp May 14 '18 at 14:31
  • Yes, clever solution. Tried it out and works great! Thanks a lot. – Dick Stada May 14 '18 at 14:43