- Counting in Python
- How to Count Elements in a List in Python
- How to Count Elements in a Tuple in Python
- How to Count Substrings in a String
- substring
- start_pos and end_pos
- How to Count the Number of Occurences in a Dictionary
- How to Count the Number of Files in a Directory in Python
- How to Count the Number of Lines in a Text File in Python
- Conclusion
- Python: Count number of lists in a given list of lists
- Visualize Python code execution:
- Python: Tips of the Day
- Count elements in a list, list of lists, nested lists in Python
- 1. Using in-built len() function
- 2.1. Count elements in list of lists Using for-loop
- 2.2. Get length of list of lists using list comprehensions
- 3. Get count of elements in Nested list
- Conclusion
Counting in Python
Counting in Python happens commonly via the count() method.
For example, let’s count how many times the word “test” appears in a list:
words = ["test", "test", "not", "a", "test"] n_test = words.count("test") print(n_test)
To check how many times a letter occurs in a string, use the count() method of a string.
num_ls = "Hello world".count("l") print(num_ls)
These are two common examples. In this guide, we are going to take a deeper look at counting in Python and see more example use cases.
How to Count Elements in a List in Python
Python list has a built-in method count(). It follows the syntax:
This method loops through the list and counts how many elements are equal to the value.
For example, let’s count how many times the word “hi” occurs in a list:
words = ["hi", "hi", "hello", "bye"] n_hi = words.count("hi") print(n_hi)
How to Count Elements in a Tuple in Python
Python tuple has a built-in count() method. This works the same way as the count() method of a list.
This method loops through the tuple and counts how many elements match the given value.
For example, let’s count how many times “hello” occurs in a tuple:
words = "hi", "hi", "hello", "bye" n_hello = words.count("hello") print(n_hello)
How to Count Substrings in a String
In Python, a string also has a count() method. You can use it to count how many times a character/substring occurs in a string.
The basic use case is similar to using the count() method of a list:
But the full syntax for the count() method of a string is:
string.count(substring, start_pos, end_pos)
- substring is the string you want to find out the number of occurrences for.
- start_pos is the index at which the search begins. This is an optional argument.
- end_pos is the index at which the search stops. This is also an optional argument.
Let’s see how these parameters work.
substring
You can count the number of substring matches in a string using the count() method.
For example, let’s count many times the substring ‘is’ occurs in a given sentence:
num_is = "This test is simple".count("is") print(num_is)
start_pos and end_pos
The start_pos determines from which index to start the substring search. The end_pos determines where to end the search.
For example, let’s count how many times “is” occurs, in a string but let’s ignore the first 5 characters by specifying start_pos 5.
num_is = "This test is simple".count("is", 5) print(num_is)
The word “is” occurs twice in the full string. But the count() method returns 1 because we ignore the first 5 characters.
As another example, let’s count how many times the substring “is” occurs in a string again. This time let’s ignore the first 4 characters and the last 9. In other words, let’s set start_pos at 4 and end_pos at 9.
num_is = "This test is simple".count("is", 4, 9) print(num_is)
Even though the word “is” occurs twice, we get 0 as a result because we only search between characters 4 and 9.
Next, let’s take a look at how to count occurrences in a dictionary.
How to Count the Number of Occurences in a Dictionary
A Python dictionary can only have one unique key. Thus, counting the number of specific keys is meaningless, as it is always 0 or 1.
But a dictionary can hold multiple identical values. To count the number of specific values in a dictionary:
You can get all the values of a dictionary with the values() method. This returns a view object. You can convert the view object to a list using the list() function.
For example, let’s count how many times a value of 5 occurs in a dictionary:
data = < "age": 5, "number_of_siblings": 3, "name": "Lisa", "address": "Imaginary street 7", "favorite_food": "Spaghetti", "favorite_number": 5 >n_fives = list(data.values()).count(5) print(n_fives)
Now you have learned how to use the count() method in Python to count occurrences in iterables in Python.
Last but not least, let’s go through 2 common tasks that involve counting in which you cannot use the count() method.
How to Count the Number of Files in a Directory in Python
To count the number of files in a directory, use the os module’s walk() method.
import os path, dirs, files = next(os.walk("/Users/Jack/Desktop")) num_files = len(files) print(num_files)
How to Count the Number of Lines in a Text File in Python
To count the number of lines in a text file:
- Open the file.
- Read the file line by with the split() method.
- Count the number of lines resulting from the split.
# Remember to specify the correct path for the file. file = open("example.txt","r") # Split the file contents by new line into a list content_list = file.read().split("\n") # Loop through the lines and count how many there are num_lines = 0 for i in content_list: if i: num_lines += 1 print(num_lines)
Conclusion
Today, you learned about counting in Python.
The count() method is a built-in utility for lists, tuples, and strings. It can be used to count how many times a specific item occurs in the sequence.
Thanks for reading. I hope you enjoy it.
Python: Count number of lists in a given list of lists
Write a Python program to count the number of lists in a given list of lists.
Sample Solution:
Python Code:
def count_list(input_list): return len(input_list) list1 = [[1, 3], [5, 7], [9, 11], [13, 15, 17]] list2 = [[2, 4], [[6,8], [4,5,8]], [10, 12, 14]] print("Original list:") print(list1) print("\nNumber of lists in said list of lists:") print(count_list(list1)) print("\nOriginal list:") print(list2) print("\nNumber of lists in said list of lists:") print(count_list(list2))
Original list: [[1, 3], [5, 7], [9, 11], [13, 15, 17]] Number of lists in said list of lists: 4 Original list: [[2, 4], [[6, 8], [4, 5, 8]], [10, 12, 14]] Number of lists in said list of lists: 3
Pictorial Presentation:
Visualize Python code execution:
The following tool visualize what the computer is doing step-by-step as it executes the said program:
Python Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource’s quiz.
Follow us on Facebook and Twitter for latest update.
Python: Tips of the Day
Getting the last element of a list:
some_list[-1] is the shortest and most Pythonic.
In fact, you can do much more with this syntax. The some_list[-n] syntax gets the nth-to-last element. So some_list[-1] gets the last element, some_list[-2] gets the second to last, etc, all the way down to some_list[-len(some_list)], which gives you the first element.
You can also set list elements in this way. For instance:
>>> some_list = [1, 2, 3] >>> some_list[-1] = 5 # Set the last element >>> some_list[-2] = 3 # Set the second to last element >>> some_list [1, 3, 5]
Note that getting a list item by index will raise an IndexError if the expected item doesn’t exist. This means that some_list[-1] will raise an exception if some_list is empty, because an empty list can’t have a last element.
- Weekly Trends
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join
- JavaScript functions Exercises
- Python Tutorial
- Python Array Exercises
- SQL Cross Join
- C# Sharp Array Exercises
We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook
Count elements in a list, list of lists, nested lists in Python
In this post, we are going to understand ways to Count elements in a list, list of lists, and nested lists in Python. While doing the data manipulation we need to get the length of the list, list of lists, and nested lists. So we need some techniques to do this kind of job for us.
When it comes to counting the number of elements in the list first idea that comes to our mind is the list. count() or else we can use len() method of the list. Let us understand with an example how we can use both of them. Ways to get number elements in a list, list of lists, nested lists in Python
1. Using in-built len() function
The len() is an in-built method in python that takes an iterable( string, tuple, dictionary, list) as an argument and returns the integer number as the size or length of the iterable. Let us understand with an example:
animal_list = ['dog','cat','mouse','cat','bee','cat','cat','rat'] length_of_list = len(animal_list) print('length of list is =',length_of_list)
#program to count the number of elements in the list of lists python list_of_lists = ['dog',[10,16],[1,5,7],['a','bc'], 'cat', 'bee', 'cat','cat'] len_list_of_lists = len(list_of_lists) print('length of list of lists is =',len_list_of_lists)
length of list of lists is = 8
2.1. Count elements in list of lists Using for-loop
As we saw above the len() method does not count elements of the list in the parent list, but we can count a total number of elements including the list in the parent list using the for a loop. We are looping over the list of lists, for each element len() function returning length by counting a number of characters in the string type element.
But as we can see if the elements inside the list of the list, len() method return its length by counting the total number of character by taking the example of the element ‘dog’ in the list so the list length would be 3. so on for all elements.
#program to count the number of elements in the list of lists python list_of_lists = ['dog',[10,16],[1,5,7],['a','bc'], 'cat', 'bee', 'cat', 'cat'] lists_elements_count = 0 for ele in list_of_lists: lists_elements_count += len(ele) print('length of list of lists is =',lists_elements_count)
length of list of lists is = 22
2.2. Get length of list of lists using list comprehensions
Another simple method to do this by using lesser code is by using the list comprehensions. Let us understand, How does it work?. Firstly create a new list consisting of a length of parent and list inside parent list as per list below the new list would be [15,0,2,3,2] and pass the list and count the sum of elements of the new list it would be 22.
#program to length of list of lists in python list_of_lists = ['dog','cat','bee','cat','cat',[],[10,16],[1,5,7],['a','bc']] elements_count = sum( [ len(ele) for ele in list_of_lists]) print('length of list of lists is =',elements_count)
length of list of lists is = 22
3. Get count of elements in Nested list
Here, we are calling the function recursively to get the length of the nested list. The function runs recursively to check the type of element in the list and run a loop over the element of the list and return the elements count.
#program to length of nested list in python nested_list = ['dog','cat',['bee',[10,16,[23,24]],[1,5,7],45],['a','bc'],[40,[3,4]]] def get_nested_length(list): size = 0 for item in list: if type(item) == list: size += get_nested_length(item) else: size+=1 return size #calling the upper define method print("length of nested list is = ",get_nested_length(nested_list))
length of nested list is = 5
Conclusion
In this article we learnt about the different ways to get the length of the list of lists in Python. I hope you will find these methods helpful in your applications.Happy Learning!!