1

I am just wondering if there is any better way of modifying the specific item in the list of list using List comprehension? In below example, I am squaring the second item of each list inside list, but, I don't want to eliminate inner list comprehension.

l = [
[1,2,3,],
[4,5,6,],
[7,8,9,],
]

nl = [[num**2 if i==1 else num for i, num in enumerate(x)] for x in l]
print nl
2
  • Are you trying to modify l in-place or create a new list nl with list comprehension? Commented Nov 2, 2017 at 2:29
  • 4
    Did you try for x in l: x[1] = x[1]**2 Commented Nov 2, 2017 at 2:30

2 Answers 2

2

Not sure how to keep the inner comprehension but you could do something like this:

def square_idx_one(sl):
    sl[1] **= 2
    return sl

l = [
[1,2,3,],
[4,5,6,],
[7,8,9,],
]

nl = [square_idx_one(sl) for sl in l]
print (nl)

result:

[[1, 4, 3], [4, 25, 6], [7, 64, 9]]

But if you're modifying the original I think a for loop probably edges this solution for performance, not to mention memory

Sign up to request clarification or add additional context in comments.

Comments

2

In your case, simply

print [[x, y**2, z] for x, y, z in l]

would do the job and says more explicitly what is going on. In general, do

from itertools import izip
p = (1, 2, 1) # element 0 power 1
#             # element 1 power 2
#             # element 2 power 1
# ...
print [[x**power for x, power in izip(row, p)] for row in l]

1 Comment

For this specific example, yes, but it doesn't scale well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.