1

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
  • 5,567
  • 4
  • 38
  • 76

2 Answers2

5

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
  • 497,756
  • 71
  • 530
  • 681
2

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
  • 13,430
  • 7
  • 40
  • 80
  • 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