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]]"""