Count Total Words in Array of Strings

Count total words across all strings.

IntermediatePhase 6 - Category 2: Array & String CombinationsExample 9 of 10
count-total-words-in-array-of-strings.py
1# Take array of strings
2n = int(input("Enter number of strings: "))
3arr = []
4for i in range(n):
5 arr.append(input(f"String {i+1}: "))
6
7# Count words
8total_words = 0
9for s in arr:
10 words = s.split()
11 total_words += len(words)
12
13print(f"Total words: {total_words}")

Output

Enter number of strings: 3
String 1: Hello World
String 2: Programming
String 3: Python Java
Total words: 5

What's going on

Split each string and count words.

Key Concepts:

Split each string
Count words in each
Sum all counts