Splice two lists

Ben Cartwright bencvt at gmail.com
Sat May 6 21:38:40 EDT 2006


danmcleran at yahoo.com wrote:
> Is there a good way to splice two lists together without resorting to a
> manual loop? Say I had 2 lists:
>
> l1 = [a,b,c]
> l2 = [1,2,3]
>
> And I want a list:
>
> [a,1,b,2,c,3] as the result.

Our good friend itertools can help us out here:

  >>> from itertools import chain, izip
  >>> x = ['a', 'b', 'c']
  >>> y = [1, 2, 3]
  >>> list(chain(*izip(x, y)))
  ['a', 1, 'b', 2, 'c', 3]
  >>> # You can splice more than two iterables at once too:
  >>> z = ['x', 'y', 'z']
  >>> list(chain(*izip(x, y, z)))
  ['a', 1, 'x', 'b', 2, 'y', 'c', 3, 'z']
  >>> # Cleaner to define it as a function:
  >>> def splice(*its):
          return list(chain(*izip(*its)))
  >>> splice(x, y)
  ['a', 1, 'b', 2, 'c', 3]
  >>> splice(x, y, z)
  ['a', 1, 'x', 'b', 2, 'y', 'c', 3, 'z']

--Ben




More information about the Python-list mailing list