1

Is it possible, while using the map() function in python (2.7) to return more than one variable? I tried doing something like this,

class obj1:

    def __init__(self,var):
        self.var = var

    def func1(self,a):

        b = [a**2 + y + self.var for y in range(4)]
        c = [a**3 + y + self.var for y in range(4)]
        return b, c

list1 = [obj1(x) for x in range(10)]
b,c = map(lambda x: x.func1(), list1)

but it says it has too many values to unpack. so I tried to do:

d = map(lambda x: x.func1(), list1)

but it returns a list of tuples instead of the two lists that I wanted.

So, my question is, is there any efficient way of returning two lists from a map function? Thanks in advance.

Bach
  • 6,145
  • 7
  • 36
  • 61
danvilar
  • 13
  • 3
  • Can you post the full traceback? – aIKid Feb 24 '14 at 11:46
  • Also, i see that `x` is an integer. Why would you call `x.func1`? – aIKid Feb 24 '14 at 11:47
  • Your logic is flawed as well.. You're returning a tuple pair of list for each iteration. The results is 10 pairs, not 2 lists. – aIKid Feb 24 '14 at 11:49
  • I already corrected the code above and I know I'm returning a list of tuples. I wanted to return b as list and c as another list – danvilar Feb 24 '14 at 11:51
  • `def __init__(var)` must be `def __init__(self, var)`, `def func1(a)` should be `def func1(self, a)`. –  Feb 24 '14 at 11:53
  • possible duplicate of [A Transpose/Unzip Function in Python (inverse of zip)](http://stackoverflow.com/questions/19339/a-transpose-unzip-function-in-python-inverse-of-zip) – podshumok Feb 24 '14 at 11:56

1 Answers1

1

You'd need to unpack each values first:

b, c = [], []
for i, j in map(lambda x: x.func1(), list1):
    b.append(i)
    c.append(j)

Also it might be just here, but you're missing self on both of your methods.

aIKid
  • 26,968
  • 4
  • 39
  • 65
  • 1
    I think this is as clean as it's going to get. `zip` has a nasty edge case when the input list is empty, and a double-list-comprehension solution or `zip` with a `len` check both fail if the input is an iterator. – user2357112 Feb 24 '14 at 12:05
  • Thanks for the answer. This is just an example, the full code is really big and I made some mistakes. However I already corrected them. I'm going to try this in a bit, but I'm afraid that extra iteration will slow down the code. I'll give some feedback in like 10 minutes or so. – danvilar Feb 24 '14 at 12:15
  • There's only two iterations, and i'm positive this is as close as you can get. – aIKid Feb 24 '14 at 12:20
  • Yup, this does the trick. It slows downs my code, but that's because of the huge amount of data. Thank you very much! – danvilar Feb 24 '14 at 12:28