Count Each Element in List Python | Python Programs

#JavaInspires

 


Python Program to get count of each element in list. Here, we have taken a list with duplicates and will use SET.

Using SET:

dup_list=['A','A','A',
			'B',
			'C','C',
			'D','D','D','D','D','D']
actual_list = set(dup_list)
for x in actual_list:
	y = dup_list.count(x)
	print(x,y)

Output

A 3
B 1
D 6
C 2
[Finished in 0.1s]

Using DICTIONARY:



Python Program to get count of each element in list. Here, we have taken a list with duplicates and will use DICTIONARY

dup_list=['A','A','A',
			'B',
			'C','C',
			'D','D','D','D','D','D']

count_dic = {}
for dup in dup_list:
	if dup in count_dic.keys():
		c = count_dic[dup]
		count_dic[dup] = c+1
	else:
		count_dic[dup] = 1

for k,v in count_dic.items():
	print(k,v)

Output

A 3
B 1
C 2
D 6
[Finished in 0.1s]


Post a Comment

Previous Post Next Post