How to coerce a list of vars into a new type?

vbgunz vbgunz at
Mon Oct 2 20:35:45 CEST 2006

> I want to verify that three parameters can all be converted into
> integers, but I don't want to modify the parameters themselves.

You can twist and tweak this version OR completely redo it. In this
version a list of the conversions are returned *but* if you want to
only check if such a conversion can be made, you can return a bool
result instead of the list. Also integers are converted to floats. just
wrap the float() in an int() if you only want ints instead and wrap
again with round() or mix and do as you please to get the results you

def convertToInteger(*args):
  ''' try to convert arguments to integers and return them in a list'''

    return [float(x) for x in (args)]
  except ValueError:
    print 'convertToInteger: pass compatible args OR return a default!'

funcResult = convertToInteger('1', '2', '3')
if funcResult:  # if conversion was perfect, choose to do what you want
  # ...
  a, b, c = funcResult  # change global variables!
  x, y, z = funcResult  # create three new variables!
  print a, b, c
  print x, y, z
  # ...

More information about the Python-list mailing list