Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine lists row-wise (Python)

Tags:

python

list

Let's say I have 3 different lists

col1 = ['2006-03-28','2006-04-05','2006-04-06']
col2 = ['IBM', 'MSFT', 'IBM']
col3 = [1000, 1000, 500]

What is the most efficient way to combine those lists in another list like this:

col = [('2006-03-28', 'IBM', 1000),
       ('2006-04-05', 'MSFT', 1000),
       ('2006-04-06', 'IBM', 500)]
like image 581
majom Avatar asked Aug 19 '12 10:08

majom


People also ask

How do you combine lists in python?

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.


2 Answers

>>> col1 = ['2006-03-28','2006-04-05','2006-04-06']
>>> col2 = ['IBM', 'MSFT', 'IBM']
>>> col3 = [1000, 1000, 500]
>>> list(zip(col1, col2, col3))
[('2006-03-28', 'IBM', 1000), ('2006-04-05', 'MSFT', 1000), ('2006-04-06', 'IBM', 500)]

If your columns are already in one list you can just use zip(*cols)

like image 94
jamylak Avatar answered Oct 05 '22 20:10

jamylak


The code is as follows: Python 3.x

>>> col1 = ['2006-03-28','2006-04-05','2006-04-06']
>>> col2 = ['IBM', 'MSFT', 'IBM']
>>> col3 = [1000, 1000, 500]

>>> col = list(zip(col1 ,col2 ,col3 ))

>>> print(str(col))

[('2006-03-28', 'IBM', 1000),
 ('2006-04-05', 'MSFT', 1000),
 ('2006-04-06', 'IBM', 500)]

Just the zip() syntax by it self works for Python 2.x. Use the above code to combine lists as row wise (or as spread sheet columns) in Python 3.x.

like image 29
SDS Avatar answered Oct 05 '22 21:10

SDS