By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,950 Members | 1,019 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,950 IT Pros & Developers. It's quick & easy.

Indicate what integer element appears the most in a list

P: 1
list = [1,5,3,6,22,45,63,30,344,22,12,25,10]
I have to print the element that appears the most in my list. In this case it will be the 22.

I need some help understand where i begin.

Nov 28 '17 #1
Share this Question
Share on Google+
3 Replies

Expert Mod 2.5K+
P: 3,503
Once could use a dictionary for this. Use the value of each element in the list as the key and the count as the number for each. For each, check if its in the dictionary. If not, add it and set the value to 1. If it exists, increment the value by 1. Grab the one with the highest count.
Dec 5 '17 #2

Expert 100+
P: 1,031
Ok, I am new to python, but 30 minutes worth trying I got this:

Expand|Select|Wrap|Line Numbers
  1. del a
  2. a = {}
  3. list = [1,5,3,6,22,45,63,30,344,22,12,25,10] 
  4. m = 0
  6. for i in list:
  7.     if str(i) in a:
  8.         a[str(i)] = a[str(i)]+1
  9.     else:
  10.         a[str(i)] = 1
  11.     print i, a[str(i)]
  13. for i in a:
  14.     print a[i], i, m
  15.     if a[i]>m:
  16.        m=a[i]
  17.        k=i
  19. print k
which leaves enough room for improvement... ;)
Dec 6 '17 #3

Expert Mod 5K+
P: 9,731
You could always refer to the python documentation for Python Data Structures for more information on structures like a Dictionary as numberwhun suggested ;)

That link to the documentation gives a very good example of how to use Dictionaries to accomplish what you are trying to do.
Dec 6 '17 #4

Post your reply

Sign in to post your reply or Sign up for a free account.