0

Pretty new to python, and can't work out (or find) how to check an array based on a variable name.

Eg:

type = "world"
world_arr = []
town_arr = []

#add to an array
[type + '_arr'].append('test') <-- how?
cs95
  • 379,657
  • 97
  • 704
  • 746
user1022585
  • 13,061
  • 21
  • 55
  • 75
  • `globals()[type + '_arr'].append('test')` ? If the arrays are global/module level variables – Anand S Kumar Aug 15 '17 at 11:40
  • I don't much like the [linked duplicate question](https://stackoverflow.com/questions/9437726/how-to-get-the-value-of-a-variable-given-its-name-in-a-string). Looking up variables by name is almost always a bad idea. Asking how to do it is a classic [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). – John Kugelman Aug 15 '17 at 11:50
  • 1
    @JohnKugelman you're in luck; today I'm establishing a better canonical. – Karl Knechtel Jul 05 '22 at 00:19

1 Answers1

4

Do not look up variable names dynamically. It's a major code smell. Use a dict.

lists = {
    'world': [],
    'town': []
}

type = 'world'
lists[type].append('test')
John Kugelman
  • 349,597
  • 67
  • 533
  • 578