В этом посте мы рассмотрим, как узнать число элементов в списке Python, удовлетворяющих определенным условиям или критериям.
Если вам просто нужно найти количество конкретных элементов с списке, используйте метод .count()
>>> list_numbers = [1, 2, 2, 5, 5, 7, 4, 2, 1]
>>> print(list_numbers.count(2))
3
Существует несколько способов такого подсчета, и мы изучим каждый из них с помощью примеров. Итак, давайте начнем.
1. Использование цикла for для подсчета в списке Python
В этом фрагменте кода мы используем цикл for для подсчета элементов списка Python, удовлетворяющих условиям или критериям. Мы перебираем каждый элемент списка и проверяем условие, если оно истинно, то мы увеличиваем счетчик на 1. Это простой процесс сопоставления и подсчета для получения интересующего нас количества.
list_numbers = [78, 99, 66, 44, 50, 30, 45, 15, 25, 20]
count = 0
for item in list_numbers:
if item%5 == 0:
count += 1
print("количество элементов списка, удовлетворяющих заданному условию:", count)
количество элементов списка, удовлетворяющих заданному условию: 6
2. Применение len() со списковыми включениями для подсчета в списке Python
В представленном ниже фрагменте кода, мы используем списковые включения (list comprehension), чтобы создать новый список, элементы которого соответствует заданному условию, после чего мы получаем длину собранного списка. Это намного легче понять на примере, поэтому давайте перейдем к нему.
list_numbers = [78, 99, 66, 44, 50, 30, 45, 15, 25, 20]
element_count = len([item for item in list_numbers if item%5 == 0])
print(
"количество элементов списка, удовлетворяющих заданному условию:",
element_count
)
количество элементов списка, удовлетворяющих заданному условию: 6
Подсчет ненулевых элементов
В этом примере мы находим общее количество ненулевых элементов. Чтобы узнать число нулевых членов списка, мы можем просто изменить условие на if item == 0
.
list_numbers = [78, 99, 66, 44, 50, 30, 45, 0, 0, 0]
element_count = len([item for item in list_numbers if item != 0])
print(
"количество элементов списка, удовлетворяющих заданному условию:",
element_count
)
количество элементов списка, удовлетворяющих заданному условию: 7
3. sum() и выражение-генератор для подсчета в списке Python
В этом примере кода мы используем sum()
с генераторным выражением. Каждый элемент списка проходит проверку условием и для тех элементов, которые ему удовлетворяют, возвращается значение True
. Метод sum()
в свою очередь подсчитывает общее число истинных значений.
list_numbers = [78, 99, 66, 44, 50, 30, 45, 15, 25, 20]
count = 0
count = sum(True for i in list_numbers if i % 5 == 0)
print(
"количество элементов списка, удовлетворяющих заданному условию:",
count
)
количество элементов списка, удовлетворяющих заданному условию: 6
4. sum() и map() для подсчета элементов списка Python с условиями или критериями
Функция map(fun, iterable)
принимает два аргумента: итерируемый объект (это может быть строка, кортеж, список или словарь) и функцию, которая применяется к каждому его элементу, — и возвращает map-объект (итератор). Для применения одной функции внутри другой идеально подходит лямбда-функция. Таким образом, map()
примет первый аргумент в виде лямбда-функции.
Здесь sum()
используется с функцией map()
, чтобы получить количество всех элементов списка, которые делятся на 5.
Давайте разберемся на примере, в котором переданная лямбда-функция предназначена для фильтрации членов списка, не кратных 5.
list_numbers = [78, 99, 66, 44, 50, 30, 45, 15, 25, 20]
count = 0
count = sum(map(lambda item: item % 5 == 0, list_numbers))
print(
"количество элементов списка, удовлетворяющих заданному условию:",
count
)
количество элементов списка, удовлетворяющих заданному условию: 6
5. reduce() с лямбда-функцией для подсчета элементов списка Python с условием или критериями
Lambda — это анонимная (без имени) функция, которая может принимать много параметров, но тело функции должно содержать только одно выражение. Лямбда-функции чаще всего применяют для передачи в качестве аргументов в другие функции или для написания более лаконичного кода. В этом примере мы собираемся использовать функции sum()
, map()
и reduce()
для подсчета элементов в списке, которые делятся на 5.
Приведенный ниже код наглядно демонстрирует это.
from functools import reduce
list_numbers = [78, 99, 66, 44, 50, 30, 45, 15, 25, 20]
result_count = reduce(
lambda count, item: count + (item % 5 == 0),
list_numbers,
0
)
print(
"количество элементов списка, удовлетворяющих заданному условию:",
result_count
)
количество элементов списка, удовлетворяющих заданному условию: 6
Надеюсь, что вы узнали о различных подходах к подсчету элементов в списке Python с помощью условия или критериев для фильтрации данных.
Удачного обучения!
В этой статье мы рассмотрим, как определить количество элементов в объекте Python и при необходимости подсчитать их сумму. Также увидим, как подсчитать количество вхождений конкретного элемента.
Итак, представим, что у нас есть следующий массив:
По условию задачи мы хотим определить, сколько элементов в данном массиве, и какова сумма всех этих элементов.
В первую очередь, вспомним, что в языке программирования Python существует специальная функция, возвращающая длину списка, массива, последовательности и так далее — это len(x), где x — наша последовательность.
Если разобраться, длина последовательности из чисел — это одновременно и количество самих цифр, поэтому мы можем решить поставленную задачу следующим образом:
print(len(array)) 6 Press any key to continue . . .А для подсчёта суммы можем занести перечисление массива Python в цикл:
array = [6,2,7,4,8,1] sum = 0 for i in range(len(array)): sum = array[i] print(sum)В принципе, вопрос решён. Но, по правде говоря, перебор целочисленного массива с помощью цикла для получения суммы элементов массива — это, всё же, костыль)). Дело в том, что в Python существует встроенная функция sum(). Она вернёт нам сумму без лишних телодвижений.
def main(): array = [1,6,3,8,4,9,25,2] print(sum(array)) if name == 'main': main() 58 Press any key to continue . . .Python: количество вхождений конкретного элемента
Бывает, нам надо подсчитать число вхождений определённых элементов в списке и вернуть найденное значение. Для этого в Python есть метод count(). Вот его синтаксис:
Метод принимает аргумент x, значение которого нас интересует. И возвращает число вхождений интересующего элемента в список:
# объявляем список website_list = ['otus.ru','includehelp.com', 'yandex.by', 'otus.ru'] # подсчитываем вхождения 'otus.ru' count = website_list.count('otus.ru') print('otus.ru found',count,'times.') # подсчитываем вхождения 'yandex.by' count = website_list.count('yandex.by') print('yandex.by found',count,'times.')Итог будет следующим:
otus.ru found 2 times. yandex.by found 1 times.Также этот метод успешно работает и с кортежами:
# объявляем кортеж sample_tuple = ((1,3), (2,4), (4,6)) # условные вхождения (1,2) count = sample_tuple.count((1,2)) print('(1,2) found',count,'times.') # условные вхождения (1,3) count = sample_tuple.count((1,3)) print('(1,3) found',count,'times.')Результат:
(1,2) found 0 times. (1,3) found 1 times.Вот и всё, теперь вы знаете, как подсчитывать количество элементов в списке, массиве, кортеже в Python.
How do I get the length of a list?
To find the number of elements in a list, use the builtin function len
:
items = []
items.append("apple")
items.append("orange")
items.append("banana")
And now:
len(items)
returns 3.
Explanation
Everything in Python is an object, including lists. All objects have a header of some sort in the C implementation.
Lists and other similar builtin objects with a «size» in Python, in particular, have an attribute called ob_size
, where the number of elements in the object is cached. So checking the number of objects in a list is very fast.
But if you’re checking if list size is zero or not, don’t use len
— instead, put the list in a boolean context — it is treated as False if empty, and True if non-empty.
From the docs
len(s)
Return the length (the number of items) of an object. The argument may be a sequence (such as a string, bytes, tuple, list, or range) or
a collection (such as a dictionary, set, or frozen set).
len
is implemented with __len__
, from the data model docs:
object.__len__(self)
Called to implement the built-in function
len()
. Should return the length of the object, an integer >= 0. Also, an object that doesn’t
define a__nonzero__()
[in Python 2 or__bool__()
in Python 3] method and whose__len__()
method returns zero
is considered to be false in a Boolean context.
And we can also see that __len__
is a method of lists:
items.__len__()
returns 3.
Builtin types you can get the len
(length) of
And in fact we see we can get this information for all of the described types:
>>> all(hasattr(cls, '__len__') for cls in (str, bytes, tuple, list,
range, dict, set, frozenset))
True
Do not use len
to test for an empty or nonempty list
To test for a specific length, of course, simply test for equality:
if len(items) == required_length:
...
But there’s a special case for testing for a zero length list or the inverse. In that case, do not test for equality.
Also, do not do:
if len(items):
...
Instead, simply do:
if items: # Then we have some items, not empty!
...
or
if not items: # Then we have an empty list!
...
I explain why here but in short, if items
or if not items
is more readable and performant than other alternatives.
Python List count() method returns the count of how many times a given object occurs in a List using Python.
Python List count() method Syntax
Syntax: list_name.count(object)
Parameters:
- object: is the item whose count is to be returned.
Returns: Returns the count of how many times object occurs in the list.
Exception:
- TypeError: Raises TypeError If more than 1 parameter is passed in count() method.
Python List count() method Example
Since the first occurrence of character b is on the 3rd index, the output is 3. Here we are using Python count to get our count.
Python3
list2
=
[
'a'
,
'a'
,
'a'
,
'b'
,
'b'
,
'a'
,
'c'
,
'b'
]
print
(list2.count(
'b'
))
Output:
3
Count Tuple and List Elements Inside List
Count occurrences of List and Python Tuples inside a list using the Python count() method.
Python3
list1
=
[ (
'Cat'
,
'Bat'
), (
'Sat'
,
'Cat'
), (
'Cat'
,
'Bat'
),
(
'Cat'
,
'Bat'
,
'Sat'
), [
1
,
2
], [
1
,
2
,
3
], [
1
,
2
] ]
print
(list1.count((
'Cat'
,
'Bat'
)))
print
(list1.count([
1
,
2
]))
Output:
2 2
Exceptions while using Python list count() method
TypeError
List count() in Python raises TypeError when more than 1 parameter is passed.
Python3
list1
=
[
1
,
1
,
1
,
2
,
3
,
2
,
1
]
print
(list1.count(
1
,
2
))
Output:
Traceback (most recent call last): File "/home/41d2d7646b4b549b399b0dfe29e38c53.py", line 7, in print(list1.count(1, 2)) TypeError: count() takes exactly one argument (2 given)
Practical Application
Let’s say we want to count each element in a Python list and store it in another list or say Python dictionary.
Python3
lst
=
[
'Cat'
,
'Bat'
,
'Sat'
,
'Cat'
,
'Mat'
,
'Cat'
,
'Sat'
]
print
([ [l, lst.count(l)]
for
l
in
set
(lst)])
print
(
dict
( (l, lst.count(l) )
for
l
in
set
(lst)))
Output:
[['Mat', 1], ['Cat', 3], ['Sat', 2], ['Bat', 1]] {'Bat': 1, 'Cat': 3, 'Sat': 2, 'Mat': 1}
Last Updated :
26 Apr, 2023
Like Article
Save Article
In this article, we will discuss how we get the number of elements in a list.
Example:
Input: [1,2,3,4,5]
Output: 5
Explanation: No of elements in the list are 5Input: [1.2 ,4.5, 2.2]
Output: 3
Explanation: No of elements in the list are 3Input: [“apple”, “banana”, “mangoe”]
Output: 3
Explanation: No of elements in the list are 3
Before getting the Number of Elements in the Python List, we have to create an empty List and store some items into the list.
There are three methods to get the number of elements in the list, i.e.:
- Using Python len( ) function
- Using for loop
- Using operator length_hint function
Using Len() function to Get the Number of Elements
We can use the len( ) function to return the number of elements present in the list.
Python3
elem_list
=
[
1
,
2
,
3
,
4
]
print
(elem_list)
print
(
"No of elements in list are:"
,
len
(elem_list))
Output:
[1, 2, 3, 4] No of elements in list are: 4
Time Complexity: O(1)
Auxiliary Space: O(1)
Using for loop Get the Number of Elements
We can declare a counter variable to count the number of elements in the list using a for loop and print the counter after the loop in Python gets terminated.
Python3
item_list
=
[
1
,
2
,
3
,
4
]
count
=
0
for
i
in
item_list:
count
=
count
+
1
print
(item_list)
print
(
"No of elements in the list are:"
, count)
Output:
[1, 2, 3, 4] No of elements in the list are: 4
Time Complexity: O(n)
Auxiliary Space: O(1)
Using length_hint Get the Number of Elements in a List
Python3
from
operator
import
length_hint
l
=
[
1
,
2
,
3
,
4
]
print
(length_hint(l))
Output:
4
Time Complexity: O(1)
Auxiliary Space: O(1)
Using Sum Get the Number of Elements in a List
Python
elem_list
=
[
1
,
2
,
3
,
4
]
print
(elem_list)
print
(
"No of elements in list are:"
,
sum
(
1
for
i
in
elem_list))
Output:
4
Time Complexity: O(n), where n is the number of elements in the list
Auxiliary Space: O(1)
Using Numpy Library
Note: Install numpy module using command “pip install numpy”
Python3
import
numpy as np
elem_list
=
[
1
,
2
,
3
,
4
]
print
(elem_list)
print
(
"No of elements in list are:"
, np.size(elem_list))
Output:
[1, 2, 3, 4]
No of elements in list are: 4
Time Complexity: O(n), where n is the number of elements in the list
Auxiliary Space: O(1)
Last Updated :
15 Feb, 2023
Like Article
Save Article