0

I want to write a single-line if-else statement that does nothing if the first condition is not met. This question is very similar to what I want to achieve, but I want my code to pass (do nothing) when the condition is not met.

In other words:

# Some list
cols = ['firstname', 'middlename', 'lastname', 'dob', 'gender', 'salary']

# Filter elements in list
[col if 'name' in col else pass for col in cols]

# Expected output
> ['firstname', 'middlename', 'lastname']

After reading the comments in this other post, I also tried skipping the else statement:

[col if 'name' in col for col in cols]
> SyntaxError: invalid syntax

The syntax I want to reduce to a one-liner is:

my_list = []
for col in cols:
    if 'name' in col:
        my_list.append(col)

Can the above code be reduced to a one-liner?

Arturo Sbr
  • 4,419
  • 2
  • 23
  • 51

2 Answers2

4

pass is a statement, not a value, so it cannot be used in a conditional expression.

You want to use the filter clause of the list comprehension.

[col for col in cols if 'name' in col]

It is somewhat unfortunate that the keyword if is used in three distinct syntactic constructs (if statements, conditional expressions, and the iteration construct shared by list/dict/set comprehensions and generator expressions).

chepner
  • 446,329
  • 63
  • 468
  • 610
1

iiuc:

my_list = [col for col in cols if 'name' in col]

if statements need to come after the for loop when using list comprehension.

Lord Elrond
  • 10,935
  • 6
  • 28
  • 60
  • 2
    It's not an if statement; calling it that just reinforces the confusion between the various constructs that all use the `if` keyword. – chepner Jun 08 '21 at 13:53