Reputation: 67
I am trying to merge 2 lists like so
coordinates_X = [1, 17, 9]
coordinates_Y = [3, 5, 24]
outcome = [1, 3, 17, 5, 9, 24]
Upvotes: 0
Views: 1411
Reputation: 4778
If ordering isn't required, you can do:
coordinates_X + coordinates_Y
Also, you can use list comprehensions to output exactly what you
[ x for y in map(lambda x, y: [x, y], coordinates_X, coordinates_Y) for x in y ]
Probably not the best way to do it, but it was what occurred to me :).
Upvotes: 1
Reputation: 638
An alternate without itertools
:
result = []
for i in zip(coordinates_X,coordinates_Y):
result.extend(i)
Upvotes: 2
Reputation: 839
** the Code you can use is: **
coordinates_X = [1, 17, 9]
coordinates_Y = [3, 5, 24]
outcome =coordinates_X+coordinates_Y
Upvotes: 1
Reputation: 37319
Are the lists always the same length? If so, this will give you a list of tuples:
outcome = zip(coordinates_X, coordinates_Y)
You can then flatten that:
import itertools
outcome = list(itertools.chain.from_iterable(zip(coordinates_X, coordinates_Y)))
For 2.x, itertools
also has izip
available, which builds an iterable yielding tuples. But that's unnecessary for lists this small. On 3.x, zip
always returns an iterable.
If they're not the same length, zip
or itertools.izip
will truncate the outcome to match the shorter list. itertools.izip_longest
can extend a shorter list with a fill value specified in the call, if you need that.
Upvotes: 3