Skip to main content

Find the frequency of each element in an list in python

Python program for Find the frequency of each element in an list. Here problem description and other solutions.

class Occurrence :
	#  Function which is display array elements
	def display(self, arr) :
		i = 0
		while (i < len(arr)) :
			print( arr[i], end = "   ")
			i += 1
		
		print(end = "\n")
	
	#  Count occurrence of given list
	def frequency(self, arr) :
		#  Display given list
		self.display(arr)
		#  Create a empty map
		map = dict()
		i = 0
		while (i < len(arr)) :
			if ((arr[i] in map.keys())) :
				#  When key exists then update value
				map[arr[i]] = map.get(arr[i]) + 1
			else :
				#  Add new element
				map[arr[i]] = 1
			
			i += 1
		
		print("  Occurrence ")
		for key, value in map.items() :
			print("  ", key ," : ", value)
		
	

def main() :
	#  Array element
	arr = [1, 3, 2, 1, 4, 2, 7, 9, 1, 3, 3, 4, 7]
	task = Occurrence()
	task.frequency(arr)

if __name__ == "__main__": main()

Output

1   3   2   1   4   2   7   9   1   3   3   4   7
  Occurrence
   1  :  3
   2  :  2
   3  :  3
   4  :  2
   7  :  2
   9  :  1




Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment