Map (function, sequence), where the function returns two values

Take a look at the following Python code:

def function(x): return x, x+1 sequence = range(5) map(function, sequence) 

it returns

 [(0,1), (1,2), (2,3), (3,4), (4,5)] 

I want to get a conclusion

 [0, 1, 2, 3, 4], [1, 2, 3, 4, 5] 

This means that I want to get two function outputs in two different lists. Can I achieve this without going through my lists?

In real code, I will not have lists of integers, but instances of classes. Therefore, I can get some copy / deep copy problems that I would like to avoid.

+4
source share
3 answers

Hope this helps:

 >>> a = [(0,1), (1,2), (2,3), (3,4), (4,5)] >>> zip(*a) [(0, 1, 2, 3, 4), (1, 2, 3, 4, 5)] 

http://docs.python.org/library/functions.html#zip

+8
source
 >>> a = zip(*map(function, sequence)) >>> for i in a: print(i) ... (0, 1, 2, 3, 4) (1, 2, 3, 4, 5) 
+3
source

Another approach:

 >>> seq = range(5+1) >>> a = [seq[:-1], seq[1:]] >>> a [[0, 1, 2, 3, 4], [1, 2, 3, 4, 5]] 
+1
source

All Articles