Problem statement: If you have a list, how do you count the

  • Thread starter Thread starter jumbogala
  • Start date Start date
  • Tags Tags
    Count List
Click For Summary
SUMMARY

The discussion focuses on counting the total number of characters in a list of strings in Python. The user initially attempted to iterate through the list but only printed individual items. The recommended solution involves using the map function to create a list of string lengths and then applying the sum function to obtain the total character count. Specifically, sum(map(len, List)) effectively calculates the total, while an alternative method using len(sum(List)) is suggested for concatenating strings.

PREREQUISITES
  • Understanding of Python programming language
  • Familiarity with Python built-in functions such as len and sum
  • Knowledge of list data structures in Python
  • Basic understanding of functional programming concepts, particularly the map function
NEXT STEPS
  • Explore Python's map function in depth
  • Learn about Python string manipulation techniques
  • Investigate performance implications of different methods for counting characters in lists
  • Review updates and changes in Python versions, particularly from 2.6.1 to 3.x
USEFUL FOR

Python developers, data analysts, and anyone looking to optimize string handling and character counting in Python lists.

jumbogala
Messages
414
Reaction score
4
Problem statement:If you have a list, how do you count the

Problem statement:
If you have a list, how do you count the number of characters in that list?

For example, if the list is list=['happy', 'sad', 'angry'], how do I get the program to tell me there are 13 characters in the list?


Attempt at a solution:

I tried doing for char in list:
print char

But that only printed each item in the list one by one...

I can't think of what else to try. Any ideas?
 
Last edited:
Physics news on Phys.org


Recall that len(Obj) returns the length of a list or string.

First use the map function to get a list of lengths...
map(len,List)
returns [5,3,5]

Then (if you have version 2.3 or higher) you can sum a list of addable objects:
so
sum(map(len,List))
should return the sum of the character lengths.

But there's a simpler way. Since character stings "add" by concatenation you can simply build a single string with sum(list) then get its length:
len(sum(List))

I have an old version right now (didn't realize it) so I can't test the sum function. I'm about to update my version and check that this works.
 


Oops, I tried sum(List) on python 2.6.1 and it did not like it.

But sum(map(len,List)) works fine.
 

Similar threads

Replies
7
Views
3K
  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 1 ·
Replies
1
Views
2K
Replies
2
Views
2K
  • · Replies 2 ·
Replies
2
Views
3K
  • · Replies 2 ·
Replies
2
Views
4K
  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 1 ·
Replies
1
Views
3K
Replies
8
Views
2K
  • · Replies 17 ·
Replies
17
Views
6K