I have a list of lists. I would like to modify the nth element in each list of the list of lists using a list compresion. I think of my list of lists as rows and columns of unequal length. I want to do column operations on a list of lists. This is easily done with the for ... in ... construct.

Python 2.71 Example:

mylist = [[0,1,2,3], [2,3,4,4,5,6], [0,0,0,4,2,3]]

# Assume that I want to modiy the 4th element in each list

for l in mylist:

if len(l) >= 4 : l[3] = l[3]**2

How can the same function be achieved using list comprehension? Thanks.

x = [ y for y in mylist ]

The result is a new list, identical to the original

Now, consider that we can define a function to manipulate a function:

def fun( L, index, newValue ) :

L[ index ] = newValue

return L

And we can see how it works interactively:

>>> fun( [ 0, 1, 2, 3 ], 2, 'x' )

[0, 1, 'x', 3]

So, we could do something like:

>>> [ fun( y, 3, 'x' ) for y in mylist ]

[[0, 1, 2, 'x'], [2, 3, 4, 'x', 5, 6], [0, 0, 0, 'x', 2, 3]]

If you are comfortable with using lamda, we could use that instead of defining a "global" or "local" function