H.Choi
H.Choi

Reputation: 3223

How do i add two lists' elements into one list?

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:

list3 = ['goodboy', 'badgirl', 'tallguy', 'bigman']

I tried something like these:

list3=[]
list3 = list1 + list2

but this would only contain the value of list1

So I used for :

list3 = []
for a in list1:
 for b in list2:
  c = a + b
  list3.append(c)

but it would result in too many lists(in this case, 4*4 = 16 of them)

Upvotes: 15

Views: 18513

Answers (4)

Mani Shanmugam
Mani Shanmugam

Reputation: 51

Using zip

list3 = []
for l1,l2 in zip(list1,list2):
    list3.append(l1+l2)

list3 = ['goodboy', 'badgirl', 'tallguy', 'bigman']

Upvotes: 0

Jonathan
Jonathan

Reputation: 3034

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);

Upvotes: 1

heretolearn
heretolearn

Reputation: 6545

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]

Upvotes: 0

Xion
Xion

Reputation: 22770

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.

Upvotes: 23

Related Questions