-1

I know this question has been asked lots of times but I still cannot get the syntax right to get it to one line:

string = 'abcdea'
ab = []

for c in list(string):
    if c in ['a','b']:
        ab.append(c) 

One line (does not work):

ab.append(c) if c in ['a','b'] for c in list(string)
1
  • That problem isn't really suited for a conditional expression. You're trying to use the wrong tool for the job. You could use a list comotehsion like below, or just keep it as it is. Commented Jan 1, 2020 at 2:00

2 Answers 2

2

You are looking for list comprehension:

string = 'abcdea'

ab = [c for c in string if c in 'ab']

print(ab)

Prints:

['a', 'b', 'a']
Sign up to request clarification or add additional context in comments.

Comments

1

For the one-line syntax, the else suite is required (e.g. ab.append(c) if c in ['a','b'] else pass for c in list(string)). However, statements are not permitted as operands in the syntax.

You're looking for list comprehensions (e.g. ab = [c if c in ['a','b'] else None for c in list(string)]). However, that could put None in your list, which I don't believe that you want. List comprehensions have special syntactic sugar for these situations. You simply move the test expression to the end (e.g. ab = [c for c in list(string) if c in ['a','b']]).

In your particular case, another approach is to use filter. This can be particularly helpful for situations in which the test function is lengthy or complicated. See the following for an example:

def is_valid_char(c):
    return c in ['a','b','c','d','e','f','A','B','C','D','E','F']

ab = list(filter(is_valid_char, list(string)))

Lastly, strings are iterable, so there's no need to convert one to a list for this purpose (e.g. ab = filter(is_valid_char, string)).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.