-1

I would like to append element-wise of two lists (one in a string format). Suppose:

a = [1,2,3]
b = ['&','&','\\']

The output that I am looking is:

['1', '&', '2', '&', '3', '\\']

I tried the below code, but the answer is not the right one:

[str(x)+y for x,y in zip(a,b)] 
Output: ['1&', '2&', '3\\']
Sam S.
  • 627
  • 1
  • 7
  • 23
  • 1
    Only real tweak needed relative to the duplicate is to explicitly convert all entries to `str` (which just returns the original `str` when the value is already a `str`, or converts if not). – ShadowRanger Oct 15 '20 at 23:11
  • It is noted that although the question is also answered here: https://stackoverflow.com/questions/7946798/interleave-multiple-lists-of-the-same-length-in-python, but at the time of my question I could not find that answer even I searched for different related keywords. It might be the title of the question there or the time, 2011, that the question raised. – Sam S. Oct 15 '20 at 23:22
  • 1
    The search terms I used were `interleave python` and `round robin python`, where both "interleave" and "round robin" are ways of describing what you're trying to do. There's actually a lot of other questions like this; I'm personally a fan of the more general solution with the `itertools` `roundrobin` recipe solution (since it works even when the inputs are of varied lengths) seen [here](https://stackoverflow.com/q/31491379/364696), and [here](https://stackoverflow.com/q/64218927/364696) (a duplicate I didn't find a good duplicate target for until after I'd answered it). – ShadowRanger Oct 15 '20 at 23:51

1 Answers1

1

Try this :

[k for i in zip(map(str, a), b) for k in i]

Output :

['1', '&', '2', '&', '3', '\\']

One limitation of using zip here would be it would iterate up to length of the smallest list, either a or b. For cases like the following :

a = [1, 2, 3, 4]
b = ['&','&','\\']

the above code would produce same result ['1', '&', '2', '&', '3', '\\'] and won't bother to go beyond 3 elements. To circumvent this, you can use zip_longest.

Arkistarvh Kltzuonstev
  • 6,824
  • 7
  • 26
  • 56