EXT
EXT

Reputation: 63

Lists and lambda expression

First of all, hello, I have a little question. I'm trying to learn how to use lambda expression etc... I have this bit of code, it's an example that I need to replicate.

>>>something (lambda x:x+1, lambda y:y+10, [1, 2, 3, 4])
[2, 12, 4, 14]

I need that output and so far I got this:

l = [1,2,3,4]
def result(l):
    o = l[0::2]
    o2 = l[1::2]
    p = map(lambda x:x+1,o)
    p2 = map(lambda y:y+10,o2)
    return p,p2

First of all I know I'm returning 2 separated lists, I'm trying to figure that one out.

Is there any way to do this without having p and p2 separated? Something like this:

p = map(lambda x,y: x+1 x+10, o,o2) 

I know that line doesn't work I'm just trying to illustrate what I'm asking

Upvotes: 3

Views: 75

Answers (3)

jsbueno
jsbueno

Reputation: 110686

The other answers will work, but if your question is just one case were you need to cycle several functions to be applied to different elements of a list, and then repeat the functions - then, semantically, a combination of zip and itertools.cycle would be a nice approach:

from itertools import cycle
[f(n) for f, n in zip(cycle((lambda x: x + 1, lambda x: x + 10)), [1, 2, 3, 4])]

Output:

[2, 12, 4, 14]

Upvotes: 0

M.T
M.T

Reputation: 5231

Assuming each of the lambda expressions are used on every second value of the third argument to something you could simply overwrite the list(or alternatively make a new one):

def something(f1,f2,lst):
    for i,li in enumerate(lst):
        if not i%2: 
            lst[i] = f1(li)
        else:  
            lst[i] = f2(li)
    return lst

something (lambda x:x+1, lambda y:y+10, [1, 2, 3, 4])
#[2, 12, 4, 14]

This is by no means optimized, but it is readable.

Upvotes: 0

Moses Koledoye
Moses Koledoye

Reputation: 78554

You're using those lambda functions wrongly. Why use multiple lambda functions to process a simple list? You can use just one, with a list comprehension:

r = [1, 2, 3, 4]
func = lambda x: [v+1 if i%2==0 else v+10 for i,v in enumerate(x)]
func(r)
# [2, 12, 4, 14]

You may even prefer writing a proper function for this for readability.

Or better, you can even do without the lambda function altogether:

[v+1 if i%2 == 0 else v+10 for i,v in enumerate(x)]

Upvotes: 1

Related Questions