-2

How do I join 2 lists with elements side by side? For example:

list1 = ["they" , "are" ,"really" , "angry"]  
list2 = ["they" , "are" ,"seriously" , "angry"] 

I want output as:

list3 = [("they","they"),("are","are"),("really","seriously"),("angry","angry")]

The above looks like a list tuples though, and if the above list were columns with each word in a row, how would I append list2 to list1?

Andy Hayden
  • 359,921
  • 101
  • 625
  • 535
Hypothetical Ninja
  • 3,920
  • 13
  • 49
  • 75
  • 3
    Using [zip](http://docs.python.org/2/library/functions.html#zip). – Yuushi Feb 13 '14 at 11:53
  • 1
    this type of question has plenty in SO, please check. – James Sapam Feb 13 '14 at 11:59
  • 2
    Perhaps worth mentioning that if the lists are of uneven length, `zip` will discard the remaining elements of the longer list. You can use [itertools.izip_longest](http://docs.python.org/2/library/itertools.html#itertools.izip_longest) if this is the case. – msvalkon Feb 13 '14 at 12:04

2 Answers2

10

Use zip():

>>> list1 = ["they" , "are" ,"really" , "angry"]  
>>> list2 = ["they" , "are" ,"seriously" , "angry"] 
>>> list3 = zip(list1, list2)
>>> list3
[('they', 'they'), ('are', 'are'), ('really', 'seriously'), ('angry', 'angry')]
TerryA
  • 58,805
  • 11
  • 114
  • 143
3

This is another solution,

>>> [ (val,list2[idx]) for idx, val in enumerate(list1)]
[('they', 'they'), ('are', 'are'), ('really', 'seriously'), ('angry', 'angry')]

By the way zip() is a good solution.

Adem Öztaş
  • 20,457
  • 4
  • 34
  • 42