Aantal Python-lijsten ()

De methode count () retourneert het aantal keren dat het opgegeven element in de lijst voorkomt.

De syntaxis van de count()methode is:

 list.count (element)

count () Parameters

De count()methode heeft één argument nodig:

  • element - het element dat moet worden geteld

Retourwaarde van count ()

De count()methode retourneert het aantal keren dat het element in de lijst voorkomt.

Voorbeeld 1: gebruik van count ()

 # vowels list vowels = ('a', 'e', 'i', 'o', 'i', 'u') # count element 'i' count = vowels.count('i') # print count print('The count of i is:', count) # count element 'p' count = vowels.count('p') # print count print('The count of p is:', count) 

Uitvoer

 De telling van i is: 2 De telling van p is: 0

Voorbeeld 2: tel tuple- en lijstelementen binnen de lijst

 # random list random = ('a', ('a', 'b'), ('a', 'b'), (3, 4)) # count element ('a', 'b') count = random.count(('a', 'b')) # print count print("The count of ('a', 'b') is:", count) # count element (3, 4) count = random.count((3, 4)) # print count print("The count of (3, 4) is:", count)  

Uitvoer

 De telling van ('a', 'b') is: 2 De telling van (3, 4) is: 1

Interessante artikelen...