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?