Newbie - How to iterate list or scalar ?

Andy Dingley dingbat at codesmiths.com
Tue Aug 8 05:53:07 EDT 2006


I seem to be writing the following fragment an awful lot, and I'm sure
it's not the best and Pythonic way to do things. Any advice on better
coding style?

pluginVersionNeeded is a parameter passed into a method and it can
either be a simple scalar variable, or it can be a list of the same
variables.  My problem is how to iterate it, whether it's a a list or
not.

I can't simply throw it into the for...in loop -- if the scalar
variable were to be a string (which is considered to be atomic in my
application) then Python sees this string as iterable and iterates over
the characters in it!


    versionsNeeded = pluginVersionNeeded
    if isinstance( versionsNeeded, list):
        versionsToTest = versionsNeeded
    else:
        versionsToTest = [ versionsNeeded ]
    for versionNeeded in versionsToTest:
        pass
            

Thanks for any advice




More information about the Python-list mailing list