For example, I have a list like this:
list1 = [good, bad, tall, big]
list2 = [boy, girl, guy, man]
and I want to make a list like this:
Using zip
list3 = []
for l1,l2 in zip(list1,list2):
list3.append(l1+l2)
list3 = ['goodboy', 'badgirl', 'tallguy', 'bigman']
for this or any two list of same size you may also use like this:
for i in range(len(list1)):
list3[i]=list1[i]+list2[i]
You can use list comprehensions with zip
:
list3 = [a + b for a, b in zip(list1, list2)]
zip
produces a list of tuples by combining elements from iterables you give it. So in your case, it will return pairs of elements from list1
and list2
, up to whichever is exhausted first.
A solution using a loop that you try is one way, this is more beginner friendly than Xions solution.
list3 = []
for index, item in enumerate(list1):
list3.append(list1[index] + list2[index])
This will also work for a shorter solution. Using map() and lambda, I prefer this over zip, but thats up to everyone
list3 = map(lambda x, y: str(x) + str(y), list1, list2);