4

I intend to strip words linked by "-" in a words list. I would use starred expression because I ignore if i will obtain a list among the list with split().

I work well with constant expression:

[i for i in [*['1','2'],'1']]

yield:

['1', '2', '1']

I would obtain the same process with variables :

test=pd.DataFrame( {'columns0' :[['hanging', 'heart', 't-light', 'holder']]})
test.apply(lambda x : [e if len(e.split('-'))==1 else (*e.split('-')) for e in x ])

but as you expected it doesn't work :

  File "<ipython-input-1109-dda6b3df14bb>", line 3
    test.apply(lambda x : [e if len(e.split('-'))==1 else ( *e.split('-')) for e in x ])
                                                           ^
SyntaxError: can't use starred expression here
lelchim
  • 45
  • 6
  • `split` will always return a list. You might want to look at `itertools.chain` and check if e is a string instead. – solarc Nov 13 '18 at 23:22

2 Answers2

2

Apparently, the answer is that splats just aren't supported in list comprehensions.

The PEP concludes the abstract saying: "This PEP does not include unpacking operators inside list, set and dictionary comprehensions although this has not been ruled out for future proposals."

Source: https://www.python.org/dev/peps/pep-0448/#id6

In an answer to a similar question, @Curtis Lustmore explains that: "The assignment operator (and all variations on it) forms a statement in Python, not an expression. Unfortunately, list comprehensions (and other comprehensions, like set, dictionary and generators) only support expressions"

Source: Unable to use *= python operator in list comprehension

Charles Landau
  • 4,187
  • 1
  • 8
  • 24
  • Very useful informations, I guess it answer the question: it's not possible and not planned thus far – lelchim Nov 14 '18 at 11:53
1

Why even bother differentiating those cases? split returns a list either way, regardless of the length. Just nest the comprehension:

lambda x: [token for e in x for token in e.split('-')]
user2390182
  • 72,016
  • 6
  • 67
  • 89