I'm trying to use list comprehension to generate a new list that consists of a letter taken from a list1 directly followed (after a colon) by the words from list2 that start with that particular letter. I managed to code this using nested for loops as following:
list1=["A","B"]
list2=["Apple","Banana","Balloon","Boxer","Crayons","Elephant"]
newlist=[]
for i in list1:
newlist.append(i+":")
for j in list2:
if j[0]==i:
newlist[-1]+=j+","
resulting in the intended result: ['A:Apple,', 'B:Banana,Balloon,Boxer,']
Trying the same using list comprehension, I came up with the following:
list1=["A","B"]
list2=["Apple","Banana","Balloon","Boxer","Crayons","Elephant"]
newlist=[i+":"+j+"," for i in list1 for j in list2 if i==j[0]]
resulting in: ['A:Apple,', 'B:Banana,', 'B:Balloon,', 'B:Boxer,']
In which each time a word with that starting letter is found, a new item is created in newlist
, while my intention is to have one item per letter.
Is there a way to edit the list comprehension code in order to obtain the same result as using the nested for loops?