Searching and manipulating lists of tuples

Harold Fellermann dadapapa at googlemail.com
Mon Jun 12 09:20:45 EDT 2006


MTD wrote:
> Hello,
>
> I'm wondering if there's a quick way of resolving this problem.
>
> In a program, I have a list of tuples of form (str,int), where int is a
> count of how often str occurs
>
> e.g. L = [ ("X",1),("Y",2)] would mean "X" occurs once and "Y" occurs
> twice
>
> If I am given a string, I want to search L to see if it occurs already.
> If it does, I find the corresponding tuple and increment the integer
> part. If not, I append the new element with int = 1.
>
> e.g.
>
> algorithm(L, "X") would produce output L = [("X",2),("Y",2)]
> algorithm(L,"Z") would produce L = [("X",1),("Y",2),("Z",1)]
>
> I tried to create an algorithm of the following form:
> >>> def algorith(list,str):
> ... 	flag = True
> ... 	for l in list:
> ... 		if l[0] == str:
> ... 			l[1] += 1
> ... 			flag = False
> ... 	if flag:
> ... 		list.append((str,1))
> ...
>
>
> But:
>
> >>> algorith(L,"X")
>
> gives:
>
> Traceback (most recent call last):
>   File "<interactive input>", line 1, in ?
>   File "<interactive input>", line 5, in algorith
> TypeError: object does not support item assignment

Your approach does not work because the tuples in the list a imutable.
The problem occurs in the line l[1] += 1. You could solve the problem
by using lists of lists, rather than lists of tuples. However, if you
only
want to know the frequency of items in the list (i.e. want to build a
histogram)
and you are not interested in the original order of items in the list,
a
dictionary is suited better for this task, because you avoid the linear
time
behavior of:

def histogram(liste) :
    result = {}
    for item in liste :
        result[item] = result.get(item,0) + 1
    return result.items()




More information about the Python-list mailing list