ActiveState Code

Recipe 576718: Homogeneous list


This is a little code for making a list that can have only items from a list of types

Python
1
2
3
4
5
def homogeneous(mylist, *types):
    '''
    >>> homogeneous([ 12, 3, 4, 4.33, 3.14, 'ola', 'string', [], None, [1, 3, 3], {}], int, type(None)) => [12, 3, 4, None]
    '''
    return [item for item in mylist if type(item) in types]      

Comments

  1. 1. At 3:59 a.m. on 15 apr 2009, Kent Johnson said:

    isinstance() can take a tuple of types so your recipe is almost the same as

    [ item for item in mylist if isinstance(item, types) ]
    

    The only difference is that isinstance() allows sub-types.

Sign in to comment