generator expression works in shell, NameError in script

Chris Rebert clp2 at rebertia.com
Wed Jun 17 18:38:47 EDT 2009


On Wed, Jun 17, 2009 at 3:19 PM, ssc<steven.samuel.cole at gmail.com> wrote:
> Hello,
>
> I am trying to generate this list of tuples:
> [(0, ''), (1, 'Dr'), (2, 'Miss'), (3, 'Mr'), (4, 'Mrs'), (5, 'Ms')]
>
> My code works fine in the Python shell:
>
>>>> titles = ['Dr', 'Miss', 'Mr', 'Mrs', 'Ms',]
>>>> title_choices = [(0, '')] + list((titles.index(t)+1, t) for t in titles)
>>>> title_choices
> [(0, ''), (1, 'Dr'), (2, 'Miss'), (3, 'Mr'), (4, 'Mrs'), (5, 'Ms')]
>
> The same code run in a script fails with
> NameError: global name 'titles' is not defined
>
> Does anybody know why ? How can I fix the error ?

See what Emile said, but here's a nicer way to code it, IMHO:

titles = ['Dr', 'Miss', 'Mr', 'Mrs', 'Ms']
title_choices = zip(range(len(titles)+1), ['']+titles)

zip() to the rescue!

Cheers,
Chris
-- 
http://blog.rebertia.com



More information about the Python-list mailing list