0

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], ...]
Ahmad
  • 8,811
  • 11
  • 76
  • 141
  • It could be duplicated, but the title of the other questions is not that straightforward. So I didn't find them. – Ahmad Oct 25 '18 at 18:52

3 Answers3

7

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.

timgeb
  • 76,762
  • 20
  • 123
  • 145
2

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.

holdenweb
  • 33,305
  • 7
  • 57
  • 77
0

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.

Austin
  • 25,759
  • 4
  • 25
  • 48
  • This seems a little clumsy, and the `map` makes it harder to understand. There are easier ways to produce the needed lists. How about `list([a, b] for (a, b) in zip(x1,x2))` for example. – holdenweb Oct 25 '18 at 19:16
  • @holdenweb, `map` is never harder to understand atleast to me. Moreover, if your list is significantly large, this can perform lazy operation which is handy at times. – Austin Oct 26 '18 at 01:40
  • As can the generator expression `([a, b] for (a, b) in zip(x1,x2))` unless I am mistaken. `map` isn't the hammer that turns all Python problems into nails! – holdenweb Oct 26 '18 at 13:03