<p>Does anyone here have any useful code which uses reduce() function in python? Is there any code other than the usual + and * that we see in the examples?</p>

<p>Refer <a href="http://www.artima.com/weblogs/viewpost.jsp?thread=98196" rel="noreferrer">Fate of reduce() in Python 3000</a> by GvR</p>

[{'answer_id': 16049, 'author': 'Brendan', 'author_id': 199, 'author_profile': 'https://Stackoverflow.com/users/199', 'pm_score': 2, 'selected': False, 'text': '<p>Not sure if this is what you are after but you can <a href="http://www.google.com/codesearch" rel="nofollow noreferrer">search source code on Google</a>.</p>\n\n<p>Follow the link for a search on <a href="http://www.google.com/codesearch?q=function%3Areduce()+lang%3Apython&amp;hl=en&amp;btnG=Search+Code" rel="nofollow noreferrer">\'function:reduce() lang:python\'</a> on Google Code search</p>\n\n<p>At first glance the following projects use <code>reduce()</code></p>\n\n<ul>\n<li>MoinMoin</li>\n<li>Zope</li>\n<li>Numeric</li>\n<li>ScientificPython</li>\n</ul>\n\n<p>etc. etc. but then these are hardly surprising since they are huge projects.</p>\n\n<p>The functionality of reduce can be done using function recursion which I guess Guido thought was more explicit.</p>\n\n<p>Update:</p>\n\n<p>Since Google\'s Code Search was discontinued on 15-Jan-2012, besides reverting to regular Google searches, there\'s something called <a href="http://icodesnip.com/" rel="nofollow noreferrer">Code Snippets Collection</a> that looks promising. A number of other resources are mentioned in answers this (closed) question <a href="https://stackoverflow.com/questions/7778034/replacement-for-google-code-search">Replacement for Google Code Search?</a>.</p>\n\n<p>Update 2 (29-May-2017):</p>\n\n<p>A good source for Python examples (in open-source code) is the <a href="http://nullege.com/" rel="nofollow noreferrer">Nullege&nbsp;search&nbsp;engine</a>.</p>\n'}, {'answer_id': 16091, 'author': 'Blair Conrad', 'author_id': 1199, 'author_profile': 'https://Stackoverflow.com/users/1199', 'pm_score': 1, 'selected': False, 'text': '<p>I have an old Python implementation of <a href="http://examples.oreilly.com/upt2/split/pipegrep" rel="nofollow noreferrer">pipegrep</a> that uses reduce and the glob module to build a list of files to process:</p>\n\n<pre><code>files = []\nfiles.extend(reduce(lambda x, y: x + y, map(glob.glob, args)))\n</code></pre>\n\n<p>I found it handy at the time, but it\'s really not necessary, as something similar is just as good, and probably more readable</p>\n\n<pre><code>files = []\nfor f in args:\n    files.extend(glob.glob(f))\n</code></pre>\n'}, {'answer_id': 16198, 'author': 'Eli Courtwright', 'author_id': 1694, 'author_profile': 'https://Stackoverflow.com/users/1694', 'pm_score': 3, 'selected': False, 'text': "<p>@Blair Conrad: You could also implement your glob/reduce using sum, like so:</p>\n\n<pre><code>files = sum([glob.glob(f) for f in args], [])\n</code></pre>\n\n<p>This is less verbose than either of your two examples, is perfectly Pythonic, and is still only one line of code.</p>\n\n<p>So to answer the original question, I personally try to avoid using reduce because it's never really necessary and I find it to be less clear than other approaches.  However, some people get used to reduce and come to prefer it to list comprehensions (especially Haskell programmers).  But if you're not already thinking about a problem in terms of reduce, you probably don't need to worry about using it.</p>\n"}, {'answer_id': 21247, 'author': 'Tomi Kyöstilä', 'author_id': 616, 'author_profile': 'https://Stackoverflow.com/users/616', 'pm_score': 2, 'selected': False, 'text': "<p>After grepping my code, it seems the only thing I've used reduce for is calculating the factorial:</p>\n\n<pre><code>reduce(operator.mul, xrange(1, x+1) or (1,))\n</code></pre>\n"}, {'answer_id': 41660, 'author': 'mweerden', 'author_id': 4285, 'author_profile': 'https://Stackoverflow.com/users/4285', 'pm_score': 4, 'selected': False, 'text': '<p>The usage of <code>reduce</code> that I found in my code involved the situation where I had some class structure for logic expression and I needed to convert a list of these expression objects to a conjunction of the expressions. I already had a function <code>make_and</code> to create a conjunction given two expressions, so I wrote <code>reduce(make_and,l)</code>. (I knew the list wasn\'t empty; otherwise it would have been something like <code>reduce(make_and,l,make_true)</code>.)</p>\n\n<p>This is exactly the reason that (some) functional programmers like <code>reduce</code> (or <em>fold</em> functions, as such functions are typically called). There are often already many binary functions like <code>+</code>, <code>*</code>, <code>min</code>, <code>max</code>, concatenation and, in my case, <code>make_and</code> and <code>make_or</code>. Having a <code>reduce</code> makes it trivial to lift these operations to lists (or trees or whatever you got, for fold functions in general).</p>\n\n<p>Of course, if certain instantiations (such as <code>sum</code>) are often used, then you don\'t want to keep writing <code>reduce</code>. However, instead of defining the <code>sum</code> with some for-loop, you <em>can</em> just as easily define it with <code>reduce</code>.</p>\n\n<p>Readability, as mentioned by others, is indeed an issue. You could argue, however, that only reason why people find <code>reduce</code> less "clear" is because it is not a function that many people know and/or use.</p>\n'}, {'answer_id': 280242, 'author': 'Claudiu', 'author_id': 15055, 'author_profile': 'https://Stackoverflow.com/users/15055', 'pm_score': 6, 'selected': False, 'text': '<p>The other uses I\'ve found for it besides + and * were with and and or, but now we have <code>any</code> and <code>all</code> to replace those cases. </p>\n\n<p><code>foldl</code> and <code>foldr</code> do come up in Scheme a lot... </p>\n\n<p>Here\'s some cute usages:</p>\n\n<p><b>Flatten a list</b></p>\n\n<p>Goal: turn <code>[[1, 2, 3], [4, 5], [6, 7, 8]]</code> into <code>[1, 2, 3, 4, 5, 6, 7, 8]</code>.</p>\n\n<pre><code>reduce(list.__add__, [[1, 2, 3], [4, 5], [6, 7, 8]], [])\n</code></pre>\n\n<p><b>List of digits to a number</b></p>\n\n<p>Goal: turn <code>[1, 2, 3, 4, 5, 6, 7, 8]</code> into <code>12345678</code>.</p>\n\n<p>Ugly, slow way:</p>\n\n<pre><code>int("".join(map(str, [1,2,3,4,5,6,7,8])))\n</code></pre>\n\n<p>Pretty <code>reduce</code> way:</p>\n\n<pre><code>reduce(lambda a,d: 10*a+d, [1,2,3,4,5,6,7,8], 0)\n</code></pre>\n'}, {'answer_id': 282206, 'author': 'jfs', 'author_id': 4279, 'author_profile': 'https://Stackoverflow.com/users/4279', 'pm_score': 6, 'selected': False, 'text': '<p><code>reduce()</code> can be used to find <a href="https://stackoverflow.com/questions/147515/least-common-multiple-for-3-or-more-numbers#147539">Least common multiple for 3 or more numbers</a>:</p>\n<pre><code>#!/usr/bin/env python\nfrom math import gcd\nfrom functools import reduce\n\ndef lcm(*args):\n    return reduce(lambda a,b: a * b // gcd(a, b), args)\n</code></pre>\n<p>Example:</p>\n<pre><code>&gt;&gt;&gt; lcm(100, 23, 98)\n112700\n&gt;&gt;&gt; lcm(*range(1, 20))\n232792560\n</code></pre>\n'}, {'answer_id': 282678, 'author': 'jfs', 'author_id': 4279, 'author_profile': 'https://Stackoverflow.com/users/4279', 'pm_score': 5, 'selected': False, 'text': '<p><code>reduce()</code> could be used to resolve dotted names (where <code>eval()</code> is too unsafe to use):</p>\n\n<pre><code>&gt;&gt;&gt; import __main__\n&gt;&gt;&gt; reduce(getattr, "os.path.abspath".split(\'.\'), __main__)\n&lt;function abspath at 0x009AB530&gt;\n</code></pre>\n'}, {'answer_id': 2701826, 'author': 'ben', 'author_id': 309368, 'author_profile': 'https://Stackoverflow.com/users/309368', 'pm_score': 2, 'selected': False, 'text': "<p>I'm writing a compose function for a language, so I construct the composed function using reduce along with my apply operator.</p>\n\n<p>In a nutshell, compose takes a list of functions to compose into a single function. If I have a complex operation that is applied in stages, I want to put it all together like so:</p>\n\n<pre><code>complexop = compose(stage4, stage3, stage2, stage1)\n</code></pre>\n\n<p>This way, I can then apply it to an expression like so:</p>\n\n<pre><code>complexop(expression)\n</code></pre>\n\n<p>And I want it to be equivalent to:</p>\n\n<pre><code>stage4(stage3(stage2(stage1(expression))))\n</code></pre>\n\n<p>Now, to build my internal objects, I want it to say:</p>\n\n<pre><code>Lambda([Symbol('x')], Apply(stage4, Apply(stage3, Apply(stage2, Apply(stage1, Symbol('x'))))))\n</code></pre>\n\n<p>(The Lambda class builds a user-defined function, and Apply builds a function application.)</p>\n\n<p>Now, reduce, unfortunately, folds the wrong way, so I wound up using, roughly:</p>\n\n<pre><code>reduce(lambda x,y: Apply(y, x), reversed(args + [Symbol('x')]))\n</code></pre>\n\n<p>To figure out what reduce produces, try these in the REPL:</p>\n\n<pre><code>reduce(lambda x, y: (x, y), range(1, 11))\nreduce(lambda x, y: (y, x), reversed(range(1, 11)))\n</code></pre>\n"}, {'answer_id': 3272453, 'author': 'ssoler', 'author_id': 170912, 'author_profile': 'https://Stackoverflow.com/users/170912', 'pm_score': 5, 'selected': False, 'text': '<p>Find the intersection of N given lists:</p>\n\n<pre><code>input_list = [[1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [3, 4, 5, 6, 7]]\n\nresult = reduce(set.intersection, map(set, input_list))\n</code></pre>\n\n<p>returns:</p>\n\n<pre><code>result = set([3, 4, 5])\n</code></pre>\n\n<p>via: <a href="https://stackoverflow.com/questions/642763/python-intersection-of-two-lists">Python - Intersection of two lists</a></p>\n'}, {'answer_id': 12026042, 'author': 'jfs', 'author_id': 4279, 'author_profile': 'https://Stackoverflow.com/users/4279', 'pm_score': 3, 'selected': False, 'text': '<p>You could replace <code>value = json_obj[\'a\'][\'b\'][\'c\'][\'d\'][\'e\']</code> with:</p>\n\n<pre><code>value = reduce(dict.__getitem__, \'abcde\', json_obj)\n</code></pre>\n\n<p>If you already have the path <code>a/b/c/..</code> as a list. For example, <a href="https://stackoverflow.com/a/11919150/4279">Change values in dict of nested dicts using items in a list</a>.</p>\n'}, {'answer_id': 12171466, 'author': 'Chris X', 'author_id': 1567046, 'author_profile': 'https://Stackoverflow.com/users/1567046', 'pm_score': 4, 'selected': False, 'text': "<p>I think reduce is a silly command. Hence:</p>\n\n<pre><code>reduce(lambda hold,next:hold+chr(((ord(next.upper())-65)+13)%26+65),'znlorabggbbhfrshy','')\n</code></pre>\n"}, {'answer_id': 12310900, 'author': 'tborg', 'author_id': 1116899, 'author_profile': 'https://Stackoverflow.com/users/1116899', 'pm_score': 2, 'selected': False, 'text': "<p>Reduce isn't limited to scalar operations; it can also be used to sort things into buckets. (This is what I use reduce for most often).</p>\n\n<p>Imagine a case in which you have a list of objects, and you want to re-organize it hierarchically based on properties stored flatly in the object. In the following example, I produce a list of metadata objects related to articles in an XML-encoded newspaper with the <code>articles</code> function. <code>articles</code> generates a list of XML elements, and then maps through them one by one, producing objects that hold some interesting info about them. On the front end, I'm going to want to let the user browse the articles by section/subsection/headline. So I use <code>reduce</code> to take the list of articles and return a single dictionary that reflects the section/subsection/article hierarchy.</p>\n\n<pre><code>from lxml import etree\nfrom Reader import Reader\n\nclass IssueReader(Reader):\n    def articles(self):\n        arts = self.q('//div3')  # inherited ... runs an xpath query against the issue\n        subsection = etree.XPath('./ancestor::div2/@type')\n        section = etree.XPath('./ancestor::div1/@type')\n        header_text = etree.XPath('./head//text()')\n        return map(lambda art: {\n            'text_id': self.id,\n            'path': self.getpath(art)[0],\n            'subsection': (subsection(art)[0] or '[none]'),\n            'section': (section(art)[0] or '[none]'),\n            'headline': (''.join(header_text(art)) or '[none]')\n        }, arts)\n\n    def by_section(self):\n        arts = self.articles()\n\n        def extract(acc, art):  # acc for accumulator\n            section = acc.get(art['section'], False)\n            if section:\n                subsection = acc.get(art['subsection'], False)\n                if subsection:\n                    subsection.append(art)\n                else:\n                    section[art['subsection']] = [art]\n            else:\n                acc[art['section']] = {art['subsection']: [art]}\n            return acc\n\n        return reduce(extract, arts, {})\n</code></pre>\n\n<p>I give both functions here because I think it shows how map and reduce can complement each other nicely when dealing with objects. The same thing could have been accomplished with a for loop, ... but spending some serious time with a functional language has tended to make me think in terms of map and reduce.</p>\n\n<p>By the way, if anybody has a better way to set properties like I'm doing in <code>extract</code>, where the parents of the property you want to set might not exist yet, please let me know.</p>\n"}, {'answer_id': 15541396, 'author': 'Sidharth C. Nadhan', 'author_id': 2094708, 'author_profile': 'https://Stackoverflow.com/users/2094708', 'pm_score': 2, 'selected': False, 'text': '<p>reduce can be used to get the list with the maximum nth element</p>\n\n<pre><code>reduce(lambda x,y: x if x[2] &gt; y[2] else y,[[1,2,3,4],[5,2,5,7],[1,6,0,2]])\n</code></pre>\n\n<p>would return [5, 2, 5, 7] as it is the list with max 3rd element +</p>\n'}, {'answer_id': 21144816, 'author': 'beardc', 'author_id': 386279, 'author_profile': 'https://Stackoverflow.com/users/386279', 'pm_score': 4, 'selected': False, 'text': '<p><strong>Function composition</strong>: If you already have a list of functions that you\'d like to apply in succession, such as:</p>\n\n<pre><code>color = lambda x: x.replace(\'brown\', \'blue\')\nspeed = lambda x: x.replace(\'quick\', \'slow\')\nwork = lambda x: x.replace(\'lazy\', \'industrious\')\nfs = [str.lower, color, speed, work, str.title]\n</code></pre>\n\n<p>Then you can apply them all consecutively with:</p>\n\n<pre><code>&gt;&gt;&gt; call = lambda s, func: func(s)\n&gt;&gt;&gt; s = "The Quick Brown Fox Jumps Over the Lazy Dog"\n&gt;&gt;&gt; reduce(call, fs, s)\n\'The Slow Blue Fox Jumps Over The Industrious Dog\'\n</code></pre>\n\n<p>In this case, method chaining may be more readable. But sometimes it isn\'t possible, and this kind of composition may be more readable and maintainable than a <code>f1(f2(f3(f4(x))))</code> kind of syntax.</p>\n'}, {'answer_id': 21956185, 'author': 'lessthanl0l', 'author_id': 3285376, 'author_profile': 'https://Stackoverflow.com/users/3285376', 'pm_score': 0, 'selected': False, 'text': '<p>Using reduce() to find out if a list of dates are consecutive:</p>\n\n<pre><code>from datetime import date, timedelta\n\n\ndef checked(d1, d2):\n    """\n    We assume the date list is sorted.\n    If d2 &amp; d1 are different by 1, everything up to d2 is consecutive, so d2\n    can advance to the next reduction.\n    If d2 &amp; d1 are not different by 1, returning d1 - 1 for the next reduction\n    will guarantee the result produced by reduce() to be something other than\n    the last date in the sorted date list.\n\n    Definition 1: 1/1/14, 1/2/14, 1/2/14, 1/3/14 is consider consecutive\n    Definition 2: 1/1/14, 1/2/14, 1/2/14, 1/3/14 is consider not consecutive\n\n    """\n    #if (d2 - d1).days == 1 or (d2 - d1).days == 0:  # for Definition 1\n    if (d2 - d1).days == 1:                          # for Definition 2\n        return d2\n    else:\n        return d1 + timedelta(days=-1)\n\n# datelist = [date(2014, 1, 1), date(2014, 1, 3),\n#             date(2013, 12, 31), date(2013, 12, 30)]\n\n# datelist = [date(2014, 2, 19), date(2014, 2, 19), date(2014, 2, 20),\n#             date(2014, 2, 21), date(2014, 2, 22)]\n\ndatelist = [date(2014, 2, 19), date(2014, 2, 21),\n            date(2014, 2, 22), date(2014, 2, 20)]\n\ndatelist.sort()\n\nif datelist[-1] == reduce(checked, datelist):\n    print "dates are consecutive"\nelse:\n    print "dates are not consecutive"\n</code></pre>\n'}, {'answer_id': 21956201, 'author': 'lessthanl0l', 'author_id': 3285376, 'author_profile': 'https://Stackoverflow.com/users/3285376', 'pm_score': 1, 'selected': False, 'text': '<p>Let say that there are some yearly statistic data stored a list of Counters.\nWe want to find the MIN/MAX values in each month across the different years. \nFor example, for January it would be 10. And for February it would be 15. \nWe need to store the results in a new Counter.</p>\n\n<pre><code>from collections import Counter\n\nstat2011 = Counter({"January": 12, "February": 20, "March": 50, "April": 70, "May": 15,\n           "June": 35, "July": 30, "August": 15, "September": 20, "October": 60,\n           "November": 13, "December": 50})\n\nstat2012 = Counter({"January": 36, "February": 15, "March": 50, "April": 10, "May": 90,\n           "June": 25, "July": 35, "August": 15, "September": 20, "October": 30,\n           "November": 10, "December": 25})\n\nstat2013 = Counter({"January": 10, "February": 60, "March": 90, "April": 10, "May": 80,\n           "June": 50, "July": 30, "August": 15, "September": 20, "October": 75,\n           "November": 60, "December": 15})\n\nstat_list = [stat2011, stat2012, stat2013]\n\nprint reduce(lambda x, y: x &amp; y, stat_list)     # MIN\nprint reduce(lambda x, y: x | y, stat_list)     # MAX\n</code></pre>\n'}, {'answer_id': 23764928, 'author': 'Aleksei astynax Pirogov', 'author_id': 590667, 'author_profile': 'https://Stackoverflow.com/users/590667', 'pm_score': 2, 'selected': False, 'text': '<pre><code>import os\n\nfiles = [\n    # full filenames\n    "var/log/apache/errors.log",\n    "home/kane/images/avatars/crusader.png",\n    "home/jane/documents/diary.txt",\n    "home/kane/images/selfie.jpg",\n    "var/log/abc.txt",\n    "home/kane/.vimrc",\n    "home/kane/images/avatars/paladin.png",\n]\n\n# unfolding of plain filiname list to file-tree\nfs_tree = ({}, # dict of folders\n           []) # list of files\nfor full_name in files:\n    path, fn = os.path.split(full_name)\n    reduce(\n        # this fucction walks deep into path\n        # and creates placeholders for subfolders\n        lambda d, k: d[0].setdefault(k,         # walk deep\n                                     ({}, [])), # or create subfolder storage\n        path.split(os.path.sep),\n        fs_tree\n    )[1].append(fn)\n\nprint fs_tree\n#({\'home\': (\n#    {\'jane\': (\n#        {\'documents\': (\n#           {},\n#           [\'diary.txt\']\n#        )},\n#        []\n#    ),\n#    \'kane\': (\n#       {\'images\': (\n#          {\'avatars\': (\n#             {},\n#             [\'crusader.png\',\n#             \'paladin.png\']\n#          )},\n#          [\'selfie.jpg\']\n#       )},\n#       [\'.vimrc\']\n#    )},\n#    []\n#  ),\n#  \'var\': (\n#     {\'log\': (\n#         {\'apache\': (\n#            {},\n#            [\'errors.log\']\n#         )},\n#         [\'abc.txt\']\n#     )},\n#     [])\n#},\n#[])\n</code></pre>\n'}, {'answer_id': 24061830, 'author': 'JulienD', 'author_id': 2197181, 'author_profile': 'https://Stackoverflow.com/users/2197181', 'pm_score': 1, 'selected': False, 'text': '<p>I have objects representing some kind of overlapping intervals (genomic exons), and redefined their intersection using <code>__and__</code>:\n</p>\n\n<pre><code>class Exon:\n    def __init__(self):\n        ...\n    def __and__(self,other):\n        ...\n        length = self.length + other.length  # (e.g.)\n        return self.__class__(...length,...)\n</code></pre>\n\n<p>Then when I have a collection of them (for instance, in the same gene), I use\n</p>\n\n<pre><code>intersection = reduce(lambda x,y: x&amp;y, exons)\n</code></pre>\n'}, {'answer_id': 24321770, 'author': 'Jian', 'author_id': 1205529, 'author_profile': 'https://Stackoverflow.com/users/1205529', 'pm_score': 3, 'selected': False, 'text': "<p><code>reduce</code> can be used to support chained attribute lookups:</p>\n\n<pre><code>reduce(getattr, ('request', 'user', 'email'), self)\n</code></pre>\n\n<p>Of course, this is equivalent to</p>\n\n<pre><code>self.request.user.email\n</code></pre>\n\n<p>but it's useful when your code needs to accept an arbitrary list of attributes.</p>\n\n<p>(Chained attributes of arbitrary length are common when dealing with Django models.)</p>\n"}, {'answer_id': 24322230, 'author': 'Jian', 'author_id': 1205529, 'author_profile': 'https://Stackoverflow.com/users/1205529', 'pm_score': 3, 'selected': False, 'text': '<p><code>reduce</code> is useful when you need to find the union or intersection of a sequence of <code>set</code>-like objects. </p>\n\n<pre><code>&gt;&gt;&gt; reduce(operator.or_, ({1}, {1, 2}, {1, 3}))  # union\n{1, 2, 3}\n&gt;&gt;&gt; reduce(operator.and_, ({1}, {1, 2}, {1, 3}))  # intersection\n{1}\n</code></pre>\n\n<p>(Apart from actual <code>set</code>s, an example of these are <a href="https://docs.djangoproject.com/en/dev/topics/db/queries/#complex-lookups-with-q-objects" rel="noreferrer">Django\'s Q objects</a>.)</p>\n\n<p>On the other hand, if you\'re dealing with <code>bool</code>s, you should use <code>any</code> and <code>all</code>:</p>\n\n<pre><code>&gt;&gt;&gt; any((True, False, True))\nTrue\n</code></pre>\n'}, {'answer_id': 32611847, 'author': 'deddu', 'author_id': 2168258, 'author_profile': 'https://Stackoverflow.com/users/2168258', 'pm_score': 1, 'selected': False, 'text': "<pre><code>def dump(fname,iterable):\n  with open(fname,'w') as f:\n    reduce(lambda x, y: f.write(unicode(y,'utf-8')), iterable)\n</code></pre>\n"}, {'answer_id': 33895037, 'author': 'MatthewRock', 'author_id': 2373609, 'author_profile': 'https://Stackoverflow.com/users/2373609', 'pm_score': 2, 'selected': False, 'text': '<p>I just found useful usage of <code>reduce</code>: <em>splitting string without removing the delimiter</em>. <a href="http://programmaticallyspeaking.com/split-on-separator-but-keep-the-separator-in-python.html" rel="nofollow">The code is entirely from Programatically Speaking blog.</a> Here\'s the code:</p>\n\n<pre><code>reduce(lambda acc, elem: acc[:-1] + [acc[-1] + elem] if elem == "\\n" else acc + [elem], re.split("(\\n)", "a\\nb\\nc\\n"), [])\n</code></pre>\n\n<p>Here\'s the result:</p>\n\n<pre><code>[\'a\\n\', \'b\\n\', \'c\\n\', \'\']\n</code></pre>\n\n<p>Note that it handles edge cases that popular answer in SO doesn\'t. For more in-depth explanation, I am redirecting you to original blog post.</p>\n'}, {'answer_id': 34625496, 'author': 'bjmc', 'author_id': 845210, 'author_profile': 'https://Stackoverflow.com/users/845210', 'pm_score': 2, 'selected': False, 'text': '<p>I used <code>reduce</code> <a href="https://github.com/kvesteri/sqlalchemy-searchable/commit/16ad8578029842ef13c39a3f406b7c462b0b9467#diff-9c140f1f7440a51eeab99543dee3587aR189" rel="nofollow">to concatenate a list of PostgreSQL search vectors</a> with the <code>||</code> operator in sqlalchemy-searchable:</p>\n\n<pre><code>vectors = (self.column_vector(getattr(self.table.c, column_name))\n           for column_name in self.indexed_columns)\nconcatenated = reduce(lambda x, y: x.op(\'||\')(y), vectors)\ncompiled = concatenated.compile(self.conn)\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/15995', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1448/']