3

I have this code in python.

import sys
list1 = ["A", "B", "C"]
list2 = [1, 2, 3]

myarg = sys.argv[1]
print len(myarg)

I will run this script from command line like this

python script.py list1

So I need a way to make the len work with the list instead of the variable, I just want to give the name of the list in the var.

I know for this example I can do

if myarg == "list1":
    print len(list1)
else if myarg == "list2"
    print len(list2)

But I have 13 lists on my script and I need a way to refer to them by the name I give on the command line.

Chris Seymour
  • 83,387
  • 30
  • 160
  • 202
usrb1n
  • 35
  • 1
  • 4
  • Does this answer your question? [How do I create a variable number of variables?](https://stackoverflow.com/questions/1373164/how-do-i-create-a-variable-number-of-variables) – wjandrea Jul 02 '20 at 01:26

3 Answers3

8

While this is entirely possible in Python, it's not needed. The best solution here is to not do this, have a dictionary instead.

import sys

lists = {
    "list1": ["A", "B", "C"],
    "list2": [1, 2, 3],
}

myarg = sys.argv[1]
print len(lists[myarg])

You note you have 13 lists in your script - where you have lots of similar data (or data that needs to be handled in a similar way), it's a sign you want a data structure, rather than flat variables. It will make your life a lot easier.

Gareth Latty
  • 86,389
  • 17
  • 178
  • 183
2

Since it is possible, and thought @Lattyware's answer is the correct one, this is how you could do it:

import sys
list1 = ["A", "B", "C"]
list2 = [1, 2, 3]

myarg = sys.argv[1]

print len(globals().get(myarg, []))

If it prints 0, then you have a bad argument on the command line.

sberry
  • 128,281
  • 18
  • 138
  • 165
1

You shouldn't, but if you really want/have to do this, you can use globals():

print len(globals()[myarg])

First make sure myarg is the name of a declared variable: if myarg in globals(): ...

Nicolas
  • 5,583
  • 1
  • 25
  • 37