One-liner to merge lists?

Albert-Jan Roskam sjeik_appie at hotmail.com
Fri Feb 25 18:04:00 EST 2022


     If you don't like the idea of 'adding' strings you can 'concat'enate:

     >>> items = [[1,2,3], [4,5], [6]]
     >>> functools.reduce(operator.concat, items)
     [1, 2, 3, 4, 5, 6]
     >>> functools.reduce(operator.iconcat, items, [])
     [1, 2, 3, 4, 5, 6]

     The latter is the functional way to spell your for... extend() loop.
     Don't forget to provide the initial value in that case lest you modify
     the input:

     >> functools.reduce(operator.iconcat, items)  # wrong
     [1, 2, 3, 4, 5, 6]
     >>> items
     [[1, 2, 3, 4, 5, 6], [4, 5], [6]]  # oops

     --
     https://mail.python.org/mailman/listinfo/python-list

   ====
   Was also thinking about reduce, though this one uses a dunder method:
   from functools import reduce
   d = {1: ['aaa', 'bbb', 'ccc'], 2: ['fff', 'ggg']}
   print(reduce(list.__add__, list(d.values())))


More information about the Python-list mailing list