Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Counting Occurrences of an Element in a List

Python Counting Occurrences of an Element in a List

Document Object Reference Manual Python3 Examples

Define a list and count how many times an element occurs in it.

For example:

输入 : lst = [15, 6, 7, 10, 12, 20, 10, 28, 10]
       x = 10
输出 : 3 

Example 1

def

countX

(

lst

,

x

)

:

    count

=

0

   

for

ele

in

lst:

       

if

(

ele

==

x

)

:

            count

=

count +

1

   

return

count

 

lst

=

[

8

,

6

,

8

,

10

,

8

,

20

,

10

,

8

,

8

]

x

=

8

print

(

countX

(

lst

,

x

)

)

The output of the above example is:


5

Example 2: using the count() method

def

countX

(

lst

,

x

)

:

   

return

lst.

count

(

x

)

 

lst

=

[

8

,

6

,

8

,

10

,

8

,

20

,

10

,

8

,

8

]

x

=

8

print

(

countX

(

lst

,

x

)

)

The output of the above example is:

5

Document Object Reference Manual Python3 Examples