[Tutor] combining tuples in a list

Brad Reisfeld brad.reisfeld@colostate.edu
Fri, 5 Apr 2002 09:58:37 -0700


Hi,
I am faced with the problem of 'combining' tuples in a list in such a way
that any tuple whose last element matches the first element of another tuple
must be combined (eliminating the duplicate element). My aim is to end up
with a list of these resulting tuples.

In practice, I have a list containing a very large number of tuples (each of
which has three items). A short example illustrating this is

inlist =
[('c','p','l'),
('d','e','f'),
('c','h','i'),
('f','w','x'),
('a','b','c'),
('g','h','i'),
('r','z','d')]

For this case we see that the last element in the fifth tuple, 'c', matches
the first element in the third tuple. Combining these (and eliminating the
duplicate match) gives ('a','b','c') '+' ('c','h','i') =>
('a','b','c','h','i')

Following this procedure exhaustively on the list above would yield the
desired result (order of tuples in the final list doesn't matter):

outlist =
[('a','b','c','h','i'),
('r','z','d','e','f','w','x'),
('g','h','i'),
('a','b','c','p','l')]


Currently, I am carrying out this procedure in a seemingly very inefficient
way by going through the list of tuples multiple times for each tuple I am
building up. I'm sure there must be a better way.

Any suggestions are appreciated.

Thanks.

-Brad