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]]"""``````
3
Contributors
4
Replies
5
Views
8 Years
Discussion Span
Last Post by pyTony

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``````

Edited by woooee: n/a

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``````

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.

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

``````>>> L = [[x*x for x in item] for item in [ [4,5,6] , [2,4,5]] ]