SpringField
SpringField

Reputation: 127

How to create a list with a range of years?

How to generate filename appropiate to the list assigned "years". I need to know how to generate the "calendar" name appropiate to the year_list. I want to add 2000 to 2013 year_list at once, because right now I have to edit and change every year number once I run the script to output different year.

year_list = [2000]
FILENAME = "calendar_2000.txt"

What I need is year_list to be 2000, 2001, 2002.. up to 2013 and the output file to be generated accordingly to the year_list numbers.

Upvotes: 1

Views: 13019

Answers (4)

jQN
jQN

Reputation: 609

I needed to create a list of values for a select field (WTForms) with a range of years. The end result is a tuple list if anyone needs something similar.

 ex: [('1950', '1950'), ('1951', '1951')]


import datetime

year = datetime.datetime.today().year
year_list = range(1950,year+1)

tupple_list = []

for year in year_list:
    tupple_list.append((year, year))

year = SelectField("YEAR", choices=tupple_list)

Upvotes: 0

user2736953
user2736953

Reputation: 156

A more typical approach would be:

for year in range(2000,2014):
   filename = "calendar_"+str(year)+".txt"

If you really want a year_list approach, the same code would work

year_list = [2000, 2001, 2002]
for year in year_list:
    filename = "calendar_"+str(year)+".txt"

Upvotes: 4

Tim Pietzcker
Tim Pietzcker

Reputation: 336348

>>> year_list = range(2000,2014)
>>> filenames = ["calendar_{0}.txt".format(year) for year in year_list]
>>> filenames
['calendar_2000.txt', 'calendar_2001.txt', 'calendar_2002.txt', 
 'calendar_2003.txt', 'calendar_2004.txt', 'calendar_2005.txt', 
 'calendar_2006.txt', 'calendar_2007.txt', 'calendar_2008.txt', 
 'calendar_2009.txt', 'calendar_2010.txt', 'calendar_2011.txt', 
 'calendar_2012.txt', 'calendar_2013.txt']
>>>

Upvotes: 6

Lennart Regebro
Lennart Regebro

Reputation: 172309

You use the builtin range function.

Upvotes: 2

Related Questions