Python – Average digits count in a List

When it is required to count average digits in a list, a simple iteration, the str() method and the division operator is used to convert numbers to strings and calculate the mean digit count.

Below is a demonstration of the same ?

Example

my_list = [324, 5345, 243, 746, 432, 463, 946787]

print("The list is :")
print(my_list)

sum_digits = 0

for ele in my_list:
    sum_digits += len(str(ele))
    
my_result = sum_digits / len(my_list)

print("The result is :")
print(my_result)

Output

The list is :
[324, 5345, 243, 746, 432, 463, 946787]
The result is :
3.5714285714285716

How It Works

The algorithm works by converting each number to a string using str() and counting its length with len(). Here's the step-by-step process ?

  • A list of integers is defined and displayed on the console.

  • A variable sum_digits is initialized to 0 to store the total digit count.

  • The list is iterated over, and for each element, we convert it to string and add its length to the sum.

  • The average is calculated by dividing total digits by the number of elements.

  • The result is displayed on the console.

Alternative Approach Using List Comprehension

You can achieve the same result more concisely using list comprehension ?

numbers = [324, 5345, 243, 746, 432, 463, 946787]

# Calculate average using list comprehension
digit_counts = [len(str(num)) for num in numbers]
average_digits = sum(digit_counts) / len(numbers)

print(f"Numbers: {numbers}")
print(f"Digit counts: {digit_counts}")
print(f"Average digits: {average_digits}")
Numbers: [324, 5345, 243, 746, 432, 463, 946787]
Digit counts: [3, 4, 3, 3, 3, 3, 6]
Average digits: 3.5714285714285716

Conclusion

Converting numbers to strings with str() and using len() provides an efficient way to count digits. The average is calculated by dividing the total digit count by the number of elements in the list.

Updated on: 2026-03-26T01:05:08+05:30

276 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements