Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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)

like image 334
H.Choi Avatar asked Jul 28 '12 17:07

H.Choi


People also ask

How do I combine two lists of elements?

Join / Merge two lists in python using + operator In python, we can use the + operator to merge the contents of two lists into a new list. For example, We can use + operator to merge two lists i.e. It returned a new concatenated lists, which contains the contents of both list_1 and list_2.

How do you combine list elements in Python?

The most conventional method to concatenate lists in python is by using the concatenation operator(+). The “+” operator can easily join the whole list behind another list and provide you with the new list as the final output as shown in the below example.

How do I add multiple lists to one list?

Using + operator The + operator does a straight forward job of joining the lists together. We just apply the operator between the name of the lists and the final result is stored in the bigger list. The sequence of the elements in the lists are preserved.


2 Answers

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.

like image 188
Xion Avatar answered Sep 27 '22 21:09

Xion


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);
like image 40
Jonathan Avatar answered Sep 27 '22 22:09

Jonathan