- 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
- Метод List.count в Python
- Как работает функция Count()?
- Python List count() Method
- Definition and Usage
- Syntax
- Parameter Values
- More Examples
- Example
- COLOR PICKER
- Report Error
- Thank You For Helping Us!
- Как использовать метод count() при работе со списками, кортежами и строками в Python
- Синтаксис
- Примеры использования
- Списки
- Кортежи
- Строки
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.
Метод List.count в Python
Из этого урока вы узнаете о методе list.count в Python. Вы увидите, как использовать его на последовательностях с помощью примеров.
Синтаксис, используемый в следующем разделе, предназначен для Python 3. Вы можете изменить его на любые другие версии Python.
Модуль count — это встроенный метод списка, который позволяет подсчитывать вхождения определенного элемента в последовательности.
Его синтаксис выглядит следующим образом:
Этот метод подсчитывает количество экземпляров элемента в списке. Смотрите пример ниже.
random_list = ["12", 12, (12, 13), 12, , 'linux', 'osx', 'win7'] random_list.count(12) # 2 random_list.count("12") # 1
Возможно, вы заметили, в первом подсчете в результате мы нашли 2 совпадения а во втором только одно. Это потому, что в списке учитывается только тот элемент, который соответствует типу данных и значению переданного параметра.
Если элемент (например, число) заключен в двойные кавычки, он обрабатывается как строка, а не как числовой тип.
Как работает функция Count()?
Этот метод принимает в качестве входных данных один аргумент, представляющий элемент, вхождение которого необходимо определить.
Он проверяет список и подсчитывает количество совпадающих экземпляров и возвращает общее количество подсчетов.
Обратите внимание, что метод List.count возвращает 0, если он получает неверный или несуществующий параметр.
random_list.count(-1) # 0 random_list.count(0) # 0 random_list.count(1000) # 0
Python List count() Method
Return the number of times the value «cherry» appears in the fruits list:
fruits = [‘apple’, ‘banana’, ‘cherry’]
Definition and Usage
The count() method returns the number of elements with the specified value.
Syntax
Parameter Values
More Examples
Example
Return the number of times the value 9 appears int the list:
points = [1, 4, 2, 9, 7, 8, 9, 3, 1]
COLOR PICKER
Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Thank You For Helping Us!
Your message has been sent to W3Schools.
Top Tutorials
Top References
Top Examples
Get Certified
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
Как использовать метод count() при работе со списками, кортежами и строками в Python
count() является методом, который можно применять к спискам, кортежам и строкам в Python. Он используется для подсчета количества вхождений указанного элемента в последовательности.
Синтаксис
Синтаксис метода count() выглядит так:
Здесь sequence — это список, кортеж или строка, в которых нужно произвести поиск, а element — это элемент, количество вхождений которого нужно подсчитать.
Примеры использования
Давайте рассмотрим несколько примеров использования метода count() для каждого из этих типов данных.
Списки
Использование метода count() в списках:
my_list = [1, 2, 3, 4, 4, 5, 4] count_of_fours = my_list.count(4) print(count_of_fours) #3
Результат выполнения этого кода будет равен «3», потому что в списке три элемента со значением «4».
Кортежи
Использование метода count() в кортежах:
my_tuple = (1, 2, 3, 4, 4, 5, 4) count_of_fours = my_tuple.count(4) print(count_of_fours) #3
Этот код также выведет число «3», потому что кортеж содержит те же элементы, что и список в предыдущем примере.
Строки
Использование метода count() в строках:
my_string = "Hello, World!" count_of_l = my_string.count('l') print(count_of_l) #3
Этот код выведет число «3», потому что символ l встречается в строке три раза.
Метод count() также можно использовать для поиска подстрок в строках:
my_string = "Hello, World!" count_of_lo = my_string.count('lo') print(count_of_lo) #1
Этот код выведет число «1», потому что подстрока lo встречается в строке только один раз.
Кроме того, метод count() возвращает ноль, если элемент не найден в последовательности:
my_list = [1, 2, 3, 4, 4, 5, 4] count_of_nines = my_list.count(9) print(count_of_nines) #0
Этот код выведет число «0», потому что элемент «9» не найден в списке.
Наконец, следует отметить, что метод count() не изменяет исходную последовательность, а только возвращает количество вхождений указанного элемента.
Метод isalnum() Python — простой способ проверки строк на наличие букв и цифр
Глобальные переменные и global в Python
Как правильно именовать функции в Python
Работа с генераторами множеств и словарей в Python на примерах
Изучаем строковые методы startswith() и endswith() в Python
Как проверить наличие символа в строке в Python: лучшие способы