Merging lists has made my brain hurt.

Brian E Gallew geek+ at andrew.cmu.edu
Wed Oct 2 12:34:23 EDT 2002


Then <huw at moving-picture.com> spoke up and said:
> NNTP-Posting-Host: soho6.sohonet.co.uk
> User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.0.0) Gecko/20020529
> 
> Hi All,
> 
> I have a list containing an arbitrary number of other lists. The 
> internal lists contain strings. For example
> lol = [
> ['aaa', 'bbb', 'ccc'],
> ['bbb', 'ccc', 'ddd'],
> ['ccc', 'ddd', 'eee']
> ]
> 
> I want to merge the three lists into a single list that only contains 
> the strings present in all three lists. In the above case I want to end 
> up with
> ['ccc']
> 
> This has me utterly stumped. Any help is appreciated.The only articles 
> about merging strings that I've managed to find so far have been about 
> merging strings so that you don't get repeats. Not quite what I'm 
> looking for.

This seems pretty easy to me.  Of course, it assumes that you can
destroy lol.

while len(lol) > 1:
  l1 = lol.pop()
  l2 = lol.pop()
  l3 = [x for x in l1 if x in l2]
  lol.append(l3)
lol=lol.pop()




More information about the Python-list mailing list