Suppose I have:
x1 = [1, 2, 3, 4]
x2 = [1, 4, 9, 16]
How can I combine them to points:
points = [[1,1],[2,4], ...]
You are looking for zip
.
>>> X1 = [1, 2, 3, 4]
>>> X2 = [1, 4, 9, 16]
>>>
>>> [list(pair) for pair in zip(X1, X2)]
>>> [[1, 1], [2, 4], [3, 9], [4, 16]]
If there's no particular reason to have the elements be lists, just use zip
on its own to produce an iterator (Python 3) or list (Python 2) of tuples.
>>> list(zip(X1, X2)) # or just zip(X1, X2) in Python 2
>>> [(1, 1), (2, 4), (3, 9), (4, 16)]
And if you don't even need all of these pairs in memory at the same time, for example if all you want to do is iterate over them, don't build a list. In Python 3, zip
produces an iterator.
>>> pairs = zip(X1, X2)
>>> for pair in pairs:
...: print(pair)
...:
(1, 1)
(2, 4)
(3, 9)
(4, 16)
>>>
>>> pairs = zip(X1, X2)
>>> next(pairs)
>>> (1, 1)
>>> next(pairs)
>>> (2, 4)
Finally, if you want the Python 3 zip
in Python 2, use izip
from itertools
.
You want the zip
function:
>>> for pair in zip(x1, x2):
... print(pair)
...
(1, 1)
(2, 4)
(3, 9)
(4, 16)
>>>
It yields a sequence of tuples, each containing a value from each of the arguments - in this case, with two arguments, you get two-element tuples.
If you really need lists, use
for pair in zip(x1, x2):
print(list(pair))
Also, be careful because if all the arguments aren't exactly the same length zip
silently drops any values remaining after the shortest argument is exhausted.
Use zip
with map
for iterating through lists simultaneously:
x1 = [1, 2, 3, 4]
x2 = [1, 4, 9, 16]
print(list(map(list, zip(x1, x2))))
# [[1, 1], [2, 4], [3, 9], [4, 16]]
zip(x1, x2)
returns a tuple of zipped values. We use map
to convert these tuples to list to match with desired output. Since, map
in Python 3 generates a map object, we cast it to list again to match with the desired output.