ewok
ewok

Reputation: 21443

python: combine 2 ordered lists into list of tuples

I have 2 lists that I want to combine into a single list of tuples, so that order is maintained and the result[i] is (first[i], second[i]). Assume that the two lists will always be of the same size. Is there a way to do this using list comprehension? So for example:

>>> first = [1,2,3]
>>> second = [4,5,6]
>>> combine(first, second)
[(1,4), (2,5), (3,6)]

I've tried a few things

[(i,j) for i in first, j in second]
[(i for i in first, j for j in second)]
[(i,j) for i,j in first, second]

None of these work. I'm just wondering if this is possible or if I have to do it using a loop.

Upvotes: 0

Views: 3900

Answers (5)

bhansa
bhansa

Reputation: 7504

>>> first = [1,2,3]
>>> second = [4,5,6]
>>> list =zip(first,second)
>>> list
[(1, 4), (2, 5), (3, 6)]

or also for lists instead of tuple, using numpy

>>> lista = [first,second]
>>> import numpy as np
>>> np.array(lista)
array([[1, 2, 3],
       [4, 5, 6]])
>>> np.array(lista)[:,0]
array([1, 4])
>>> np.array(lista)[:,1]
array([2, 5])
>>> np.array(lista)[:,2]
array([3, 6])

Upvotes: 1

Bamcclur
Bamcclur

Reputation: 2029

Use izip:

>>> first = [1,2,3]
>>> second = [4,5,6]

>>> from itertools import izip
>>> gen = izip(first, second)
>>> [(i, j) for i, j in gen]
[(1, 4), (2, 5), (3, 6)]

Upvotes: 0

Spacedman
Spacedman

Reputation: 94182

Python has a function for that:

>>> zip(first, second)
[(1, 4), (2, 5), (3, 6)]

zippedy-doo-dah

Upvotes: 5

Mary Marchini
Mary Marchini

Reputation: 718

You can use the built-in zip function:

>>> first = [1,2,3]
>>> second = [4,5,6]
>>> list(zip(first, second))
[(1,4), (2,5), (3,6)]

Upvotes: 2

user2285236
user2285236

Reputation:

Use zip:

list(zip(first, second))
Out[384]: [(1, 4), (2, 5), (3, 6)]

Upvotes: 8

Related Questions