2

I would like to do list comprehension only on the second and third element of each sub-list. I've been able to do this, but I lose the first element. I know I could do this pretty easily with a for loop, but I'd like to be pythonic (idiomatic python) and use list comprehension.

test = [[3,6,9],[3,6,9]]
v = [[x/3.0 for x in y[1:3]] for y in test]
print v

Output

[[2.0, 3.0], [2.0, 3.0]]

Desired output

[[3, 2.0, 3.0], [3, 2.0, 3.0]]

3 Answers 3

2

Just include y[:1] + in the result:

>>> test = [[3,6,9],[3,6,9]]
>>> [y[:1] + [x/3.0 for x in y[1:3]] for y in test]
[[3, 2.0, 3.0], [3, 2.0, 3.0]]

It looks like you fundamentally misunderstand comprehensions. They don't modify the original in-place, they build a new one. That's why, if you only take a part of the original, you only get a part of the original.

If you want to modify certain parts, then a loop might serve you better and there's nothing unpythonic about it.

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

2 Comments

Good one, you might want to add "+ y[3:]" at the end of the nested comprehensions to make this solution work with bigger lists.
Yeah, maybe, although he only spoke of losing the first element. If he actually does have longer sublists, I hope he can generalize it properly himself.
2

An alternative solution is to check whether you are dealing with the first element or not using a ternary operator:

v = [[elem/3.0 if idx!=0 else elem for idx, elem in enumerate(k)] for k in test]

This case would serve for all values of the list except for the first.

Comments

0

You could use the following list comprehension

>>> [[i[0]] + [j/i[0] for j in i[1:]] for i in test]
[[3, 2.0, 3.0], [3, 2.0, 3.0]]

Note this does not prevent against divide-by-zero if you are expecting the first element of each sublist to possibly be zero.

Comments

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.