By Jon

2019-05-15 16:12:32 8 Comments

I am trying to utilize list comprehension to populate a new list, which is the length of text in a DataFrame column.

So if the text is "electrical engineer", it should output 19 etc. Instead, it just fills the list with None values

I have written out list comprehension below

all_text_length = [all_text_length.append(len(i)) for i in data['all_text']]

Expecting output of integer but its None

As a workaround, I am currently using (successfully)

[all_text_length.append(len(i)) for i in data['all_text']]```


@Praveenkumar 2019-05-15 16:25:18

You are trying to append to the same list on which you are doing list comprehension. Since the append returns a None type, you are getting None. The below code should work,

all_text_length = map(len, data['all_text'])

map is a function that takes another function (first argument) and applies it to every element in an iterable (second argument) and returns a list of the results.

@Florian Hoppe 2019-05-15 16:30:20

The value before the "for" statement in the list comprehension, will be added to the list. If you place a statement in there, like


, the return value of that function will be added. Because .append() doesnt have areturn-statement in it, you get the value None as return type, wich will be added to your list.

Use the code @Prune recommended and it should work as you want.

@Prune 2019-05-15 16:16:19

Read the documentation on append: it works in-place. There is no returned value. What you've written is essentially

all_text_length = [None for i in data['all_text']]

It appears that you're trying to make a list comprehension to entirely change your list. Try this:

all_text_length = [len(i) for i in data['all_text']]

If you just need the lengths in a convenient form, would it do to form a new column? Simply apply len to the df column.

Related Questions

Sponsored Content

13 Answered Questions

[SOLVED] How to flush output of print function?

9 Answered Questions

[SOLVED] Python `if x is not None` or `if not x is None`?

11 Answered Questions

[SOLVED] How to access environment variable values?

10 Answered Questions

[SOLVED] Why is it string.join(list) instead of list.join(string)?

  • 2009-01-29 22:45:13
  • Evan Fosmark
  • 1276564 View
  • 1760 Score
  • 10 Answer
  • Tags:   python string list

34 Answered Questions

[SOLVED] How do I sort a dictionary by value?

18 Answered Questions

5 Answered Questions

[SOLVED] Creating an empty Pandas DataFrame, then filling it?

10 Answered Questions

[SOLVED] How to select rows from a DataFrame based on column values?

Sponsored Content