2

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.

1
  • Exclude i == j by putting it after the list comp. Commented Nov 22, 2022 at 8:42

2 Answers 2

2

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]
Sign up to request clarification or add additional context in comments.

1 Comment

Brilliant, thanks! I did not know I could have if's before and after the for.
2

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]

1 Comment

Thanks! I accepted the other answer only because it came before yours.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.