Python Count Occurrences in list

Home /

Table of Contents

Glance about ‘List’

A list is a collection of items, which can be of different data types, including numbers, strings, and other objects in python. Lists are defined using square brackets ‘[]‘ and items are separated by commas. Lists are mutable, meaning the elements within the list can be changed.

Example:

Python
a = [1, 2, 3, 4, 5]
b = ["apple", "banana", "cherry"]
c = [1, "apple", 3.14, True]

To count how many times an item appears on a list

In Python, you can use the ‘list.count()‘ method to count the number of times an item appears in a list.

Example:

Python
a = [1, 2, 3, 1, 2, 3, 4, 5, 6, 1]
count = a.count(1)
print(count) 

Output:

3

You can also use a for loop and an if statement to check each element in the list and increment a counter for each match.

Example:

Python
a = [1, 2, 3, 1, 2, 3, 4, 5, 6, 1]
count = 0
for i in a:
    if i == 1:
        count += 1
print(count) 

Output:

3

Repeat items in a list

You can repeat items in a list in Python using the multiplication operator ‘*‘ or list comprehension.

To repeat an item using the multiplication operator, you simply multiply the item by an integer. Here’s an example:

Python
my_list = ['apple'] * 3
print(my_list)  

Output:

'apple', 'apple', 'apple'

In this example, we have a list ‘my_list‘ containing a single string 'apple'. We use the multiplication operator ‘*‘ to repeat the string three times, resulting in a new list with three strings.

You can also use list comprehension to repeat an item. Here’s an example:

Python
my_list = ['apple' for _ in range(3)]
print(my_list)  

Output:

'apple', 'apple', 'apple'

In this example, we use list comprehension to create a new list with three strings 'apple'. The ‘for‘ loop in the list comprehension iterates three times, creating a new string 'apple' on each iteration.

Both of these methods can be used to repeat any item in a list, not just strings. For example, you could repeat numbers, boolean values, or even other lists.

Share The Tutorial With Your Friends
Twiter
Facebook
LinkedIn
Email
WhatsApp
Skype
Reddit
Other Recommended Article