12

Actually I'm trying to merge two lists to one string but keep them ordered meaning:

list1 = [1,2,3,4,5]
list2 = ["one", "two", "three", "four", "five"]

result = "1one2two3three4four5five"

(lists always have the same length but vary in contents)

At the moment I'm doing it this way:

result = ""
i = 0

for entry in list1:
    result += entry + list2[i]
    i += 1

I think there must be a more pythonic way to do this but I don't know it actually.

May someone of you can help me out on this.

0

4 Answers 4

24
list1 = [1,2,3,4,5]
list2 = ["one", "two", "three", "four", "five"]

print ''.join([str(a) + b for a,b in zip(list1,list2)])
1one2two3three4four5five
10
  • This is a generator expression used alongside str.join(). Commented Mar 29, 2013 at 12:53
  • Make it a list comprehension and it'll be faster still. By giving .join() a generator expression, Python has to create a list from it anyway because .join() needs to scan the input twice, once to calculate the total length of the output and once to generate the output. A [list comprehension] is faster than list(generator expression). Commented Mar 29, 2013 at 12:54
  • @MartijnPieters True but simplicity is probably more important
    – jamylak
    Commented Mar 29, 2013 at 12:54
  • 1
    Thanks for the help. It's exactly what i was looking for. Just have to wait another 7 minutes before accepting the answer
    – chill0r
    Commented Mar 29, 2013 at 12:57
  • 2
    Note that list comprehensions are only a better option where you know the whole thing is going to be exhausted. Commented Mar 29, 2013 at 12:58
4
>>> import itertools
>>> ''.join(map(str, itertools.chain.from_iterable(zip(list1, list2))))
1one2two3three4four5five'

Explanation:

  • zip(list1, list2) creates a list containing tuples of matching elements from the two lists:

    >>> zip(list1, list2)
    [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four'), (5, 'five')]
    
  • itertools.chain.from_iterable() flattens that nested list:

    >>> list(chain.from_iterable(zip(list1, list2)))
    [1, 'one', 2, 'two', 3, 'three', 4, 'four', 5, 'five']
    
  • Now we need to ensure that there are only strings, so we apply str() to all items using map()

  • Eventually ''.join(...) merges the list items into a single string with no separator.
4
  • I would argue this is the most flexible, pythonic answer. The advantage here is one could happily add more iterables to zip() and it would work perfectly, the other answers would all require alteration depending on the number of iterables. Commented Mar 29, 2013 at 12:58
  • 1
    @Lattyware flexible, yes but definitely overkill for this particular situation
    – jamylak
    Commented Mar 29, 2013 at 13:04
  • 2
    @Lattyware: for me, Ashwini's answer is the most pythonic - "simple is better than complex", you know.
    – georg
    Commented Mar 29, 2013 at 13:05
  • I don't really feel this is that much more complex - maybe that's just me. Commented Mar 29, 2013 at 13:10
4

Using string formatting with str.join() and zip():

>>> list1 = [1,2,3,4,5]
>>> list2 = ["one", "two", "three", "four", "five"]

>>> "".join("{0}{1}".format(x,y) for x,y in zip(list1,list2))
'1one2two3three4four5five'

zip(list1,list2) returns something like this: [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four'), (5, 'five')].

Now for each item of this list we apply the string formatting and then join the whole generator expression using str.join().

8
  • 1
    or just '{}{}'.format(*p) for p in...
    – georg
    Commented Mar 29, 2013 at 13:04
  • @thg435 This way it's clearer
    – jamylak
    Commented Mar 29, 2013 at 13:05
  • @jamylak: I'm not a big format fan, so I'd personally use "%d%s" % p for p....
    – georg
    Commented Mar 29, 2013 at 13:06
  • 1
    @thg435 you should use format(), as it might replace % based formatting sooner or later. docs.python.org/release/3.0.1/whatsnew/… Commented Mar 29, 2013 at 13:13
  • @AshwiniChaudhary: I don't think they ever dare.
    – georg
    Commented Mar 29, 2013 at 13:14
2
>>> ''.join(str(n)+s for (n,s) in zip(list1, list2))
'1one2two3three4four5five'

Here:

  • for (n,s) in zip(list1, list2) iterates over pairs of elements in list1 and list2 (i.e. 1 and "one" etc);
  • str(n)+s converts each pair into a string (e.g. "1one");
  • ''.join(...) merges the results into a single string.

Not the answer you're looking for? Browse other questions tagged or ask your own question.