Python List - Count Method

Method Name:

count

Method Signature:

count()

Overview:

  • The method returns the number of times an element appears in the list.
  • To find the number of elements in a list use the len() function.

Parameters:

element - The element whose occurence in the list needs to be counted.

Return value:

None

Example 1:

# Example Python program that finds the number of occureneces of an item in a list

# Create a list
objects =  ["Curtain",
            "Picture",
            "Curtain",
            "Wall light",
            "Table lamp",
            "Torch",
            "Pen",
            "Note pad",
            "Pen",
            "TV",
            "Telephone"];

# Element to find
objectToCount    = "Curtain";        

# Number of elements found
objectCount     = objects.count(objectToCount);    
print("There are %d %ss in the list"%(objectCount,
              objectToCount));

# Element to find
objectToCount    = "TV";        

# Number of elements found
objectCount     = objects.count(objectToCount);    
print("There are %d %ss in the list"%(objectCount,
              objectToCount));

Output:

There are 2 Curtains in the list
There are 1 TVs in the list

Example 2:

# Example Python program that finds the number
# of objects of same attributes using the count() method
class Door:
    def __init__(self, width, height, thickness):
        self.width        = width;
        self.height     = height;
        self.thickness     = thickness;

    def __eq__(self, object):
        if (self.width == object.width) and (self.height == object.height) and (self.thickness == object.thickness):
            return True;
        else:
            return False;

# Create doors
d1 = Door(3, 9, 0.2);            
d2 = Door(3, 9, 0.2);
d3 = Door(3, 10, 0.2);
d4 = Door(3, 9, 0.2);

# Create a list of doors
doors = [d1, d2, d3, d4];

# Find doors whose width = 3, height = 9, thickness = 0.2
doorCount = doors.count(d1);
print("Doors found with the same attributes: %d"%doorCount);


Output:

Doors found with the same attributes: 3

 


Copyright 2023 © pythontic.com