deadghost
deadghost

Reputation: 5227

Python Can I add a tuple to a generator?

I want to add ('', 'Day') to the front. Right now it makes a drop down menu for the numbers 1 through 31 and I want a 'Day' choice at the top.

DAY_CHOICES = (
    # I was hoping this would work but apparently generators don't work like this.
    # ('', 'Day'),
    (str(x), x) for x in range(1,32)
)

# I'll include this in the snippet in case there's some voodoo I can do here
from django import forms
class SignUpForm(forms.Form):
    day = forms.ChoiceField(choices=DAY_CHOICES)

Upvotes: 0

Views: 1578

Answers (3)

eyquem
eyquem

Reputation: 27585

DAY_CHOICES = ( (str(x),x) if x>0 else('','Day') for x in range(0,32) )

Upvotes: 1

andreaspelme
andreaspelme

Reputation: 3310

This seems like a bad use of generators. A generator is not a list, it is a function that generates a sequence of values, so it is not possible to "add a tuple to a generator".

The generator will be exhausted after the model initialization. You might for instance want to use DAY_CHOICES again later -- which will not be possible.

If you do not have any very specific reason for using a generator here, I would recommend turning DAY_CHOICES to a list instead:

DAY_CHOICES = [('', 'Day')] + [(str(x), x) for x in range(1,32)]

Upvotes: 1

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799130

You want itertools.chain().

for i in itertools.chain(('foo', 'bar'), xrange(1, 4)):
  print i

Upvotes: 6

Related Questions