Python | Average String length in list

Sometimes, while working with data, we can have a problem in which we need to gather information of average length of String data in list. This kind of information might be useful in Data Science domain. Let’s discuss certain ways in which this task can be performed.

Method #1 : Using list comprehension + sum() + len()
The combination of above functions can be used to perform this task. In this we compute lengths of all Strings using list comprehension and then divide the sum by length of list using len() and sum().

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Average String lengths in list
# using list comprehension + sum() + len()
  
# initialize list 
test_list = ['gfg', 'is', 'best', 'for', 'geeks']
  
# printing original list 
print("The original list : " + str(test_list))
  
# Average String lengths in list
# using list comprehension + sum() + len()
temp = [len(ele) for ele in test_list]
res = 0 if len(temp) == 0 else (float(sum(temp)) / len(temp)) 
  
# printing result
print("The Average length of String in list is : " + str(res))

chevron_right


Output :

The original list : ['gfg', 'is', 'best', 'for', 'geeks']
The Average length of String in list is : 3.4

 

Method #2 : Using map() + sum() + len()
The combination of above functions can also be used to perform this task. In this, we compute lengths using map(). Rest all the logic is similar to above method.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Average String lengths in list
# using map() + sum() + len()
  
# initialize list 
test_list = ['gfg', 'is', 'best', 'for', 'geeks']
  
# printing original list 
print("The original list : " + str(test_list))
  
# Average String lengths in list
# using map() + sum() + len()
res = sum(map(len, test_list))/float(len(test_list))
  
# printing result
print("The Average length of String in list is : " + str(res))

chevron_right


Output :

The original list : ['gfg', 'is', 'best', 'for', 'geeks']
The Average length of String in list is : 3.4



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.