2

Lets say i have one list a and a list of lists b:

a = ['1','2','3']
b = [['Hello'],['I'],['am']]

How could i go about getting the following output?

b = [['Hello','1'],['I','2'],['am','3']]

I have tried various things unsuccesfully like the following.

for i in a:
    for j in range(b):
        j.append(i[j])
print(b)

EDIT: I was looking for a way to do this, in case the two lists is not of the same length, which the duplicate does not answer. If you look in the comments on the accepted answer, you will fin the solution though.

briyan
  • 81
  • 1
  • 8

2 Answers2

1

you could use a list comprehension with zip:

r = [[s[0], n] for (n, s) in zip(a, b)]

update after comments:

if your lists are not of the same length you can use itertools.zip_longest and something like

from itertools import zip_longest

r = [s if n is None else
     [n] if s is None else
     [s[0], n] for (n, s) in zip_longest(a, b)]
hiro protagonist
  • 44,693
  • 14
  • 86
  • 111
  • Will this work if lists arent of the same length? – briyan Jun 13 '17 at 19:50
  • Another option: `[u + [v] for u, v in zip(b, a)]` – PM 2Ring Jun 13 '17 at 19:51
  • 1
    @briyan What do you want to do with the leftover stuff if the lists aren't the same length? – PM 2Ring Jun 13 '17 at 19:51
  • Just add nothing to those elements. – briyan Jun 13 '17 at 19:52
  • `zip` will stop after the first list is exhausted. but there is [`itertools.zip_longest`](https://docs.python.org/3/library/itertools.html#itertools.zip_longest) where you can add a `fillvalue`. – hiro protagonist Jun 13 '17 at 19:52
  • Thanks! will accept this. – briyan Jun 13 '17 at 19:58
  • @briyan Here's my version modified to handles either list being longer than the other. `[u if v is None else [v] if u is None else u + [v] for u, v in zip_longest(b, a)]` – PM 2Ring Jun 13 '17 at 20:13
  • @briyan It's a shame that you didn't mention that you need to handle unequal list lengths in your question, and how you want to handle them, since the answers in the question that juanpa.arrivillaga used to close this question don't really show how to do that. If you just use `zip_longest` without including a test like I used then your lists end up having `None` (or some other default value) in them. – PM 2Ring Jun 13 '17 at 21:16
  • @PM2Ring Yes, i will update the question when i get home, and point people to your comment. I figured it out with your guys' help - so hopefully others will too. – briyan Jun 13 '17 at 21:31
0

Try this;

>>> a = ['1','2','3']
>>> b = [['Hello'],['I'],['am']]
>>> ab = [[b[i][0], a[i]] for i in range(len(a))]
Memduh
  • 836
  • 8
  • 18