views:

131

answers:

2

I'm not expierenced in python. I need to define field 'year' with range restriction. Now i'm using this code, but I think there exists shorten way to do this.

YEAR_CHOICE = []
for year in range(2020,1899,-1):
   YEAR_CHOICE += [(year, year)]
year = models.PositiveSmallIntegerField('Year', choices=YEAR_CHOICE, default=0)

Is therу any ways to define 2-tuples in one line? May be I can make field what I need in other way? Thank you!

+8  A: 

You should look at using a list comprehension:

YEAR_CHOICE = [(year,year) for year in xrange(2020,1899,-1)]

You should also usage xrange instead of range. xrange is preferred as it returns the values one by one rather than creating the whole list.

Dave Webb
For those who may not have seen the term before, search for "list comprehension"
Thomas L Holaday
Or click on the link added to my answer.
Dave Webb
xrange() is preferred usage up to python 2.6. xrange() is discontinued in python 3.0 and range() performs in 3.0 as xrange() did in previous versions.
hughdbrown
+3  A: 

zip the range with itself:

YEAR_CHOICE = zip(*[range(2020,1899,-1)]*2)

or use list comprehension:

YEAR_CHOICE = [(year,year) for year in range(2020,1899,-1)]
vartec
The zip code is clever, but even an experienced Python programming would need to think about it for a few moments to discern what it's actually doing and why it works. I'd personally recommend the longer but clearer list comprehension.
Eli Courtwright
Yeah, zip(*[range(2020,1899,-1)]*2) is zip(range(2020,1899,-1),range(2020,1899,-1))
vartec