# Revision history [back]

Hi,

Here is a simple solution. Given a list that contains several elements, you may use the method .count() to get the multiplicity

sage: l = [1, 3, "four", 1, "four", 1, 3, 1, 3]
sage: l.count(1)
4
sage: l.count("four")
2


Now a more involved solution is to get a dictionnary. You can achieve this with a simple for loop:

sage: d = {}
sage: for i in l:
....:     if i not in d:
....:         d[i] = 0
....:     d[i] += 1
sage: print d
{'four': 2, 1: 4, 3: 3}


If you have a list of matrices, you need to be careful as a matrix is not necessarily immutable (which implies that it can not be used as a key of a dictionnary).

sage: d = {}
sage: m = identity_matrix(4)
sage: d[m] = 4
Traceback (most recent call last)
...
TypeError: mutable matrices are unhashable


In order to be able to use your matrices in a dictionnary, you need to set them immutable

sage: M = MatrixSpace(ZZ, 2)
sage: l = [M.random_element() for i in xrange(500)]  # 500 random matrices
sage: for m in l: m.set_immutable()                  # set them immutable
sage: d = {}
sage: for i in l:
....:     if i not in d:
....:         d[i] = 0
....:     d[i] += 1
sage: for m,mult in d.iteritems(): print m.list(), mult
[5, -1, 2, -1] 1
[-1, 1, 0, 0] 1
[-6, 0, 2, 2] 1
...
[2, -3, 0, 1] 1


Vincent

Hi,

Here is a simple solution. Given a list that contains several elements, you may use the method .count() to get the multiplicity

sage: l = [1, 3, "four", 1, "four", 1, 3, 1, 3]
sage: l.count(1)
4
sage: l.count("four")
2


Now a more involved solution is to get build a dictionnary. You can achieve this with a simple It is possible to do it using count() but it is not very elegant. Another way is to do a for loop:

sage: d = {}
sage: for i in l:
....:     if i not in d:
....:         d[i] = 0
....:     d[i] += 1
sage: print d
{'four': 2, 1: 4, 3: 3}


If you have a list of matrices, you need to be careful as a matrix is not necessarily immutable (which implies that it can not be used as a key of a dictionnary).

sage: d = {}
sage: m = identity_matrix(4)
sage: d[m] = 4
Traceback (most recent call last)
...
TypeError: mutable matrices are unhashable


In order to be able to use your matrices in a dictionnary, you need to set them immutable

sage: M = MatrixSpace(ZZ, 2)
sage: l = [M.random_element() for i in xrange(500)]  # 500 random matrices
sage: for m in l: m.set_immutable()                  # set them immutable
sage: d = {}
sage: for i in l:
....:     if i not in d:
....:         d[i] = 0
....:     d[i] += 1
sage: for m,mult in d.iteritems(): print m.list(), mult
[5, -1, 2, -1] 1
[-1, 1, 0, 0] 1
[-6, 0, 2, 2] 1
...
[2, -3, 0, 1] 1


Vincent