0

I need to create a ORDERED list that contains a series of sub-lists. But I'm not sure how to iterate through known variables.

Here's an example. Let's say I have the following sub-lists:

list_0 = [0, 1, 2]
list_1 = [3, 4, 5, 6]
list_2 = [7, 8, 9]

I'm trying to append the lists to a larger list list_all:

list_all = [ [0, 1, 2], [3, 4, 5, 6], [7, 8, 9] ]

So I'm trying to iterate through the variable names but I'm not sure this is possible?

list_all = [list_{num}.format(num=i) for i in range(3)]
# SyntaxError

This seems to work if list_all contains strings of the known variables but I don't need the variables obviously, I need the data within those variables.

list_all = ['list_{num}'.format(num=i) for i in range(3)]
print list_all
# ['list_0', 'list_1', 'list_2']

So I guess the question is how can I dynamically create and execute python variable names? I need to do this because the number of lists changes with each use case.

2
  • What you should do is use a list (or other data structure) instead of naming your variables "foo_#". Then you can very simply and naturally iterate through your list to do what you want. Commented Jan 25, 2017 at 17:02
  • 2
    don't create variables list_0, list_1 but list or dictionary list[0], list[1] Commented Jan 25, 2017 at 17:05

1 Answer 1

1

If you really, really need this, you could get the variables and their values from the globals() or locals() dictionaries.

>>> list_0 = [0, 1, 2]
>>> list_1 = [3, 4, 5, 6]
>>> list_2 = [7, 8, 9]
>>> [globals()["list_{}".format(i)] for i in range(3)]
[[0, 1, 2], [3, 4, 5, 6], [7, 8, 9]]

However, almost certainly it would be a better idea to store the individual lists as part of list_all to begin with, and access them as list_all[0] etc. instead of list_0:

>>> list_all = []
>>> list_all.append([0, 1, 2])
>>> list_all.append([3, 4, 5, 6])
>>> list_all.append([7, 8, 9])
>>> list_all[0]
[0, 1, 2]
Sign up to request clarification or add additional context in comments.

1 Comment

Great answer thanks! I also figured out eval() works in this case too

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.