Home > Enterprise >  generator object preventing list comprehension
generator object preventing list comprehension

Time:12-28

I am trying to turn a string into a list of words, then into a list of word lengths. For example:

myString = 'this is a test string with test words in it'
myString = myString.split(' ')
myNums = []
for i in range(len(myString)):
    myNums.append(len(myString[i]))
print(myNums)
>>[4, 2, 1, 4, 6, 4, 4, 5, 2, 2]

I think I should be able to do this using list comprehension, for example:

myNums = [len(myString[i] for i in range(len(myString)))]

But when I do, I get TypeError: object of type 'generator' has no len()

I can't figure out where the generator object is, and why it's incompatible with list comprehension. Any tips/suggestions appreciated, thanks.

CodePudding user response:

You can simplify your expression by iterating on elements of your list and not on index:

myNums = [len(w) for w in myString]
print(myNums)

# Output
[4, 2, 1, 4, 6, 4, 4, 5, 2, 2]

You can also use functional programming:

myNums = list(map(len, myString))
print(myNums)

# Output:
[4, 2, 1, 4, 6, 4, 4, 5, 2, 2]

CodePudding user response:

You have a misplaced closing parenthesis:

myNums = [len(myString[i] for i in range(len(myString)))]
                         ^                             |
                         |___should go there___________|
  • Related