Search code examples
pythonlistnonetypemap-function

Python : Map function with none type list as parameter


I want to pass a list of None in a map function but it doesn't work.

a = ['azerty','uiop']
b = ['qsdfg','hjklm']
c = ['wxc','vbn']
d = None

def func1(*y):
    print 'y:',y

map((lambda *x: func1(*x)), a,b,c,d)

I have this message error:

TypeError: argument 5 to map() must support iteration.

Solution

  • Replace None with an empty list:

    map(func1, a or [], b or [], c or [], d or [])
    

    or filter the lists:

    map(func1, *filter(None, (a, b, c, d)))
    

    The filter() call removes d from the list altogether, while the first option gives you None values to your function call.

    I removed the lambda, it is redundant here.

    With the or [] option, the 4th argument is None:

    >>> map(func1, a or [], b or [], c or [], d or [])
    y: ('azerty', 'qsdfg', 'wxc', None)
    y: ('uiop', 'hjklm', 'vbn', None)
    [None, None]
    

    Filtering results in 3 arguments to func1:

    >>> map(func1, *filter(None, (a, b, c, d)))
    y: ('azerty', 'qsdfg', 'wxc')
    y: ('uiop', 'hjklm', 'vbn')
    [None, None]
    

    You could use itertools.starmap() as well, but that gets a little verbose:

    >>> list(starmap(func1, zip(*filter(None, (a, b, c, d)))))
    y: ('azerty', 'qsdfg', 'wxc')
    y: ('uiop', 'hjklm', 'vbn')
    [None, None]