Coercing a list of values

Andrew M. Kuchling akuchlin at cnri.reston.va.us
Tue May 18 15:04:55 EDT 1999


A friend wrote me with the following question:

>You see, given a tuple, I'd like
>to coerce the elements to the same type using standard Python coercion
>rules.  That is, the tuple: (1, 1, 0L) should be converted to (1L, 1L, 0L)
>and (0.1, 4, 5) to (0.1, 4.0, 5.0).  

	Now, coerce(x,y) returns a tuple containing the values of x
and y coerced to the same type.  But for a whole list, I see no better 
way to do this than to loop over the list *twice*, like this:

def coerce_seq(seq):
    L = list(seq)

    # Coerce the first value of the list with each of the other
    # elements.  This should result in the 'item' variable getting the
    # most inclusive type needed.

    item = L[0]
    for i in range(1, len(L)):
        item, dummy = coerce( item, L[i])

    # Coerce everything to the same type as 'item'
    for i in range(len(L)):
        L[i], dummy = coerce(L[i], item )

    return L

print coerce_seq( (1,1,0L) )
print coerce_seq( (.1,4,5) )
print coerce_seq( (.1,4j,5) )

	This prints the correct results:
[1L, 1L, 0L]
[0.1, 4.0, 5.0]
[(0.1+0j), 4j, (5+0j)]

	But it seems inelegant.  Is there a smart way of doing this
that doesn't need two passes over the list?  

-- 
A.M. Kuchling			http://starship.python.net/crew/amk/
Perhaps the most striking difference between Malory's _Morte d'Arthur_ and
Tennyson's _Idylls of the King_ is that Malory's women are all human beings,
and that Tennyson's are, in greater or less degree, prizes for good conduct.
    -- Robertson Davies, _A Voice from the Attic_





More information about the Python-list mailing list