Welcome, guest | Sign In | My Account | Store | Cart

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

Python, 5 lines
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]      

1 comment

Kent Johnson 15 years ago  # | flag

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.

Created by marlonamor on Tue, 14 Apr 2009 (MIT)
Python recipes (4591)
marlonamor's recipes (2)

Required Modules

  • (none specified)

Other Information and Tasks