Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python – Average String length in list
Calculating the average length of strings in a list is a common task in Python. This involves finding the total length of all strings and dividing by the number of strings. Python offers several approaches including statistics.mean(), for loops, and map() functions.
Using statistics.mean() Function
The statistics module provides a built-in mean() function that calculates averages efficiently ?
import statistics
words = ["Sharpener", "book", "notepad", "pencil"]
lengths = [len(word) for word in words]
avg_length = statistics.mean(lengths)
print("Average string length:", avg_length)
Average string length: 6.5
Using For Loop
A simple for loop iterates through each string, accumulates the total length, and calculates the average ?
words = ["Sharpener", "book", "notepad", "pencil"]
total_length = 0
for word in words:
total_length += len(word)
avg_length = total_length / len(words)
print("Average string length:", avg_length)
Average string length: 6.5
Using map() and sum() Functions
The map() function applies len() to each string, then sum() adds up all lengths ?
words = ["book", "notepad", "pencil"]
total_length = sum(map(len, words))
avg_length = total_length / len(words)
print("Average string length:", avg_length)
Average string length: 5.666666666666667
Using List Comprehension with sum()
List comprehension provides a concise way to calculate string lengths ?
words = ["python", "programming", "tutorial", "code"]
avg_length = sum(len(word) for word in words) / len(words)
print("Average string length:", avg_length)
Average string length: 6.75
Comparison
| Method | Readability | Performance | Best For |
|---|---|---|---|
statistics.mean() |
High | Good | Statistical calculations |
| For Loop | High | Good | Beginners, clear logic |
map() + sum() |
Medium | Fast | Functional programming |
| List Comprehension | High | Fast | Pythonic code style |
Conclusion
Use statistics.mean() for statistical operations or list comprehension with sum() for concise Pythonic code. For loops offer the clearest approach for beginners to understand the calculation process.
