Johnny Metz
Johnny Metz

Reputation: 5965

python: dynamically create and execute existing variable names

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.

Upvotes: 0

Views: 92

Answers (1)

tobias_k
tobias_k

Reputation: 82899

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]

Upvotes: 1

Related Questions