-1

So I need to append two list together. Each element of the List one attached to each element of List two. So it the final list will be something like this: ['L1[0]L2[0]','L1[1]L2[1]','L1[2]L2[2]','L1[3]L2[3]']. I keep running into the problem of putting a for loop inside another for loop but the result is having the first loop element repeat multiple times. I understand this isn't working, if any one can give me a nudge or somewhere to look into information on this sort of subject. As always thank you for the help!! Here is my code:

def listCombo(aList):
       myList=['hello','what','good','lol','newb']
       newList=[]
       for a in alist:
             for n in myList:
                   newList.append(a+n)
       return newList

Example:

List1=['florida','texas','washington','alaska']
List2=['north','south','west','east']

result= ['floridanorth','texassouth','washingtonwest','','alaskaeast']
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
JamalCrawford..
  • 177
  • 2
  • 12

2 Answers2

2

You need to use zip.

[i+j for i,j in zip(l1, l2)]

Example:

>>> List1=['florida','texas','washington','alaska']
>>> List2=['north','south','west','east']
>>> [i+j for i,j in zip(List1, List2)]
['floridanorth', 'texassouth', 'washingtonwest', 'alaskaeast']
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
  • clean & pythonic, +1 – Ayush Dec 04 '15 at 03:06
  • I like, though there are a couple other approaches that could potentially go faster on CPython for larger inputs (not usually worth it, but worth noting): `map(''.join, zip(l1, l2))` (wrapped in `list()` on Py3 if you're not just iterating the result once or need a true `list` for some other reason). Or with imports, `from operator import concat`, `map(concat, l1, l2)`, which makes the use line even simpler. :-) – ShadowRanger Dec 04 '15 at 04:46
0

list comprehension over zip:

[x[0]+x[1] for x in zip(list1,list2)]

>>> [x[0]+x[1] for x in zip(['1','2','3'],['3','4','5'])]
# ['13', '24', '35']
ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
Ayush
  • 3,695
  • 1
  • 32
  • 42