Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

Count Total Words in Array of Strings

Count words across a Python list of strings. Students split each text independently, ignore empty whitespace tokens, and accumulate counts across the inputs.

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

In this one

  • Count independent token lists
  • Accumulate across strings
  • Ignore extra whitespace

How it works

  1. 1

    Split each stored string without a separator argument.

  2. 2

    Add len(words) to total_words.

  3. 3

    Print the shared count after all strings.

Edge cases

Does whitespace-only text add one word?

Does whitespace-only text add one word?

No. It adds zero.

Are strings concatenated before counting?

Are strings concatenated before counting?

No. Each is split separately.

What's going on

For each s, split creates its nonempty whitespace-delimited tokens. len(words) is added to the shared total_words.

Blank strings and runs of spaces contribute zero. Punctuation remains attached to tokens, so this is whitespace token counting rather than a language-aware parser. Separate string boundaries stay separate; ending one input with red and beginning another with blue counts two words.

Does whitespace-only text add one word? No. It adds zero.

Are strings concatenated before counting? No. Each is split separately.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

Where does the total live?

Pick an answer to check it.

Question 2

Does whitespace-only text add one word?

Pick an answer to check it.

Questions people ask

Does whitespace-only text add one word?

No. It adds zero.

Are strings concatenated before counting?

No. Each is split separately.

Where does the total live?

Outside the per-string loop.