How to exclude a specific element from a list comprehension with conditionals

Question:

I am trying to use a list comprehension to extract specific elements from a list, using conditionals on the list indices.
When the list indices differ, specific operations need to happen.
When the list indices are the same, no element should be added.
The latter is what I do not know how to do, except by adding '' and removing it afterwards.

Example (simpler than my actual case, but conceptually the same):

x = [0, 1, 2, 3, 4]
i = 2
x2 = [2 * x[j] - x[i] if j > i else 2 * x[i] - x[j] if j < i else '' for j in x]
x2.remove('')
x2
# [4, 3, 4, 6]

How would you exclude the case where i == j a priori?

I would have thought that just not having else '' at the end would work, but then I get an invalid_syntax error.

I suppose in essence I am looking for a neutral element for the list comprehension.

Asked By: user6376297

||

Answers:

You can put if clauses after for to filter some elements.

x2 = [2 * x[j] - x[i] if j > i else 2 * x[i] - x[j] for j in x if j != i]
Answered By: ILS

You can apply two kind of conditionals to a list comprehension. The one you are applying is applied to every element that make it to that point of code to get a value, that is why you need the else. You also want the filter behaviour (discard values that don’t meet a condition), so you have to apply another conditional after the for, which decides which values to consider for the generated list:

x = [0, 1, 2, 3, 4]
i = 2
x2 = [2 * x[j] - x[i] if j > i else 2 * x[i] - x[j] for j in x if j != i]
Answered By: Marta Fernandez
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.