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)]
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.
>>> 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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With