2

I've found this question and one thing in the original code bugs me:

>>> x="Alpha_beta_Gamma"
>>> words = [y for y in x.split('_')]

What's the point of doing this: [y for y in x.split('_')]? split already returns a list and items aren't manipulated in this list comprehension. Am I missing something?

Community
  • 1
  • 1
gronostaj
  • 2,231
  • 2
  • 23
  • 43

2 Answers2

8

You're correct; there's no point in doing that. However, it's often seen in combination with some kind of filter or other structure, such as [y for y in x.split('_') if y.isalpha()].

TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97
2

There is no difference in result but using list comprehension in this case in not a good way and in redundant!

>>> x="Alpha_beta_Gamma"
>>> [y for y in x.split('_')]
['Alpha', 'beta', 'Gamma']
>>> x.split('_')
['Alpha', 'beta', 'Gamma']
Mazdak
  • 105,000
  • 18
  • 159
  • 188