-2
keywords = ['a', 'b', '(c)']
keywords = [keyword for keyword in keywords if "(" in keyword and ")" in keyword]

I want the output to be:

keywords = ['a', 'b', 'c']

How to modify the list comprehension to get the result without using a loop?

marlon
  • 6,029
  • 8
  • 42
  • 76
  • 5
    I can't understand. If this is "using a loop", then **every** list comprehension does that. That's what the `for` means. If you simply mean "how do I use a list comprehension to get this result?", then first think carefully about how you would write the code to get `'c'` from `'(c)'` but `'a'` from `'a'`, **then** write a list comprehension to apply that to the entire list. The question is not actually about writing the list comprehension - *if you know how to process one element, you know how to solve the full problem*. – Karl Knechtel Sep 28 '22 at 21:12
  • In order to do that, it is first necessary to specify the problem more clearly: **What is the rule that tells you** that `'(c)'` should turn into `'c'`? What if you had `'((d))'` instead, for example - would it turn into just `'d'`, or into `'(d)'`? What if you had `')e('`? Or `'((f'`? – Karl Knechtel Sep 28 '22 at 21:14
  • My data won't be that complex. It can only be in the form of '(c)'. – marlon Sep 28 '22 at 21:25
  • 1
    Then there are many rules you could use that will work. The question is still not clear. – Karl Knechtel Sep 29 '22 at 01:06

3 Answers3

2

Try strip:

>>> keywords = ['a', 'b', '(c)']
>>> [kw.strip('()') for kw in keywords]
['a', 'b', 'c']
>>>
gog
  • 10,367
  • 2
  • 24
  • 38
  • strip('()'): Does the strip remove all leading and trailing chars in the argument? – marlon Sep 28 '22 at 21:09
  • @marlon Yes, just like [the documentation says](https://docs.python.org/3.4/library/stdtypes.html#str.strip) or just try it: `'()()((x))()()'.strip('()')` -> `x` – Mark Tolonen Sep 28 '22 at 21:13
0

strip works. Alternate solution using replace() as well:

>>> keywords = ['a', 'b', '(c)']
>>> [kw.replace('(','').replace(')','') for kw in keywords]
['a', 'b', 'c']
Squirtle
  • 11
  • 3
  • 1
    This is not an alternative to strip. Its behavior is significantly different when the characters occur inside the string. For example compare with a string like `'(ca()hdb)'`. – Mark Sep 28 '22 at 21:19
  • This is not as good as the strip('()') in its simplicity. – marlon Sep 28 '22 at 21:22
  • definitely not a simpler solution. Also just realized you meant to ask to just trim the front and the end / first layer of parenthesis – Squirtle Sep 28 '22 at 21:33
  • `str.removeprefix('(')` and `str.removesuffix(')')` would be better as an alternative to `strip('()')` than `str.replace()` in this case – Arifa Chan Sep 28 '22 at 21:54
0

A list comprehensions in Python is a type of loop

Without using a loop:

keywords = ['a', 'b', '(c)']
keywords = list(map(lambda keyword: keyword.strip('()'), keywords))
Arifa Chan
  • 947
  • 2
  • 6
  • 23