0

say I have a list, x:

x=[1,2,3,4,1]

How do I search this list so that I can find the number of occurrences of a number and the list position it occurs in?

I know about using the method x.count(num), but this only shows number of occurrences not list position. Thanks

Andrés Pérez-Albela H.
  • 4,003
  • 1
  • 18
  • 29
James Brightman
  • 857
  • 2
  • 13
  • 23
  • `index` will do that, e.g. `x.index(3)` gives `2`. It only returns the first index however. – 101 Dec 07 '15 at 02:55
  • is there a way to do the same sort of operation but make it return more than just the first index? – James Brightman Dec 07 '15 at 03:02
  • There certainly is! https://stackoverflow.com/questions/6294179/how-to-find-all-occurrences-of-an-element-in-a-list – 101 Dec 07 '15 at 03:05

2 Answers2

2

Just play with Counter..

>>> from collections import Counter
>>> x=[1,2,3,4,1]
>>> Counter(x)
Counter({1: 2, 2: 1, 3: 1, 4: 1})
>>> {y:[i for i,j in enumerate(x) if j == y] for y in Counter(x)}
{1: [0, 4], 2: [1], 3: [2], 4: [3]}
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
0

You can generate a new list to store the occurrence positions, And the length of new list is the count.

>>> x = [1, 2, 3, 4, 1]
>>> y = [ i for i in xrange(len(x)) if x[i] == 1 ]
>>> y
[0, 4]
>>> len(y)
2
eph
  • 1,988
  • 12
  • 25