2

I am generating these 2 lists using list comprehension.

lists = ['month_list', 'year_list']
for values in lists:
    print [<list comprehension computation>]

>>> ['2012', '2011', '2010', '2009', '2008', '2007', '2006', '2005', '2004', '2003']
>>> ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']

I want to append these 2 dynamically generated lists to this list names.
for example :

month_list = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']  
year_list = ['2012', '2011', '2010', '2009', '2008', '2007', '2006', '2005', '2004', '2003']
2
  • 2
    Using dynamic variable names is a huge mess. Don't do it. Ever. You are not using not PHP. Simply put those lists in a dict instead of using separate variables for them. Commented May 9, 2012 at 5:37
  • What does <list comprehension computation> look like? Because the best answer will depend on it. (It most likely won't contain a loop, though.) Commented May 9, 2012 at 7:24

4 Answers 4

3

Sounds to me like you should be using references instead of names.

lists = [month_list, year_list]

But list comprehensions can only create a single list regardless, so you'll need to rethink your problem.

Sign up to request clarification or add additional context in comments.

Comments

2
month_list = []
year_list = []
lists = [month_list, year_list]
dict = {0 : year_list, 1:month_list}

for i, values in enumerate(data[:2]):
    dict[i].append(<data>)

print 'month_list - ', month_list[0]
print 'year_list - ', year_list[0]

>>> month_list -  ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
>>> year_list -  ['2012', '2011', '2010', '2009', '2008', '2007', '2006', '2005', '2004', '2003']

1 Comment

Why string keys? Why not integer keys?
2

You can add global variables to the modul's namespace and connect values to them with this method:

globals()["month_list"] = [<list comprehension computation>]

Read more about namespaces in Python documents.

Or you can store these list in a new dictionary.

your_dictionary = {}
your_dictionary["month_list"] = [<list comprehension computation>]

Comments

1

Why use strings in the first place?

Why not just do...

lists = [month_list, year_list]
for list_items in lists:
    print repr(list_items)

after you define the two lists?

Comments

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.