Question

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.
Was it helpful?

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]

OTHER TIPS

Make 2nd argument to map a list or tuple:

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

The error message pretty much says it all: None is not iterable. Arguments to map should be iterable:

map(func, *iterables) --> map object

Make an iterator that computes the function using arguments from
each of the iterables.  Stops when the shortest iterable is exhausted.

Depending on what you want to achieve, you can:

  • change None to an empty list;
  • map your function on a list of [a, b, c, d]

Also note that you can map func1 directly, without a lambda:

map(func1, *iterables)

2nd argument d should be a SEQUENCE , make it as a list or tuple..

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top