Member Avatar for cyon

How do I apply a function to a selective number of values in a list of lists using a list comprehension without filtering the values that are not passed through the function?

Specifically, I have a list:
[[4, 5, 6], [2, 4, 5]]

And I want to square only the 0th and 1st indices of each sublist:
[[16, 25, 6], [4, 16, 5]]

My attempt (see code below) doesn't work, because len(x)-1 omits the 2nd index and they are filtered out.

Any help greatly appreciated,
cyon

def square(x):
    return x*x

L = [ [4,5,6] , [2,4,5] ]

print 'Before', L

L[:] = [ [ square(x[column]) for column in range(len(x)-1) ] for x in L ]

print 'Squared', L

"""actual output of above code:
Before [[4, 5, 6], [2, 4, 5]]
Squared [[16, 25], [4, 16]]"""

"""desired output:
Before [[4, 5, 6], [2, 4, 5]]
Squared [[16, 25, 6], [4, 16, 5]]"""

This is a tricky one (note the parens in the statement).

L = [ [4,5,6] , [2,4,5] ]
new_L = [ (y if ctr > 1 else y*y) for x in L for ctr, y in enumerate(x)]
print new_L
Member Avatar for cyon

This is a tricky one (note the parens in the statement).

L = [ [4,5,6] , [2,4,5] ]
new_L = [ (y if ctr > 1 else y*y) for x in L for ctr, y in enumerate(x)]
print new_L

Thanks for your reply.

new_L is actually [16, 25, 6, 4, 16, 5] instead of my desired output, [ [16,25,6] , [4,16,5] ], but I will try to implement the strategies you introduced.

Member Avatar for cyon

This did it:
L[:] = [ [ (item if i==2 else square(item)) for i, item in enumerate(x) ] for x in L ]

commented: well done ! +3

Or

>>> L = [[x*x for x in item] for item in [ [4,5,6] , [2,4,5]] ]
>>> L
[[16, 25, 36], [4, 16, 25]]
>>>
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.