17. Calculating the string length

Hi sir/ma’am, while i was writing my code i had previous practice problems in my mind and hence i used the range and len function in my code. However, when i checked the answer it was very simple. how to decide when to use and when to keep it simple like in this particular problem. Please guide me the proper method to approach the practice problems as i am having difficulty in solving them. Any help or any material i need to refer extra?

Screen Link:

My Code:

word_len = []
for i in range(len(words)):

What I expected to happen:
[6, 10, 5, 10, 7, 4, 11, 8, 11, 12, 4, 3, 4, 5, 5, 10, 7, 8, 6, 4]

What actually happened:

['tissue', 'psychology', 'blind', 'assessment', 'dynamic', 'hero', 'circulation', 'merchant', 'publication', 'interference', 'show', 'joy', 'sour', 'aloof', 'grass', 'distortion', 'exclude', 'pressure', 'bullet', 'calf']

This code solves it in one line.

word_len = [len(word) for word in words]

The first thing to do is understand the problem and write a pseudocode before even hitting the key board.

The problem wants you to find length of a string. How do you do that? You use the len function. You have to apply the len function to every word in the words list.

Therefore you need to loop through the list either using a for loop or list comprehension. When you loop through the words list, you do not need the index position, you need the content of the list itself. Unless, you want to use the index to access the words list which is unnecessary because you can loop through each item on the list.


1 Like