-2

I have 2 lists :

x = ['a','b','c']
y = ['d','e','f']

I need a single list of lists :

z = [['a','d'],['b','e'],['c','f']]

What I tried :

# Concatenate x and y with a space
w = []
for i in range(len(x)):
    w.append(x[i]+" "+y[i])

# Split each concatenated element into a sublist
z = []
for i in range(len(w)):
    z.append(w[i].split())

Is there a way to do this directly without using 2 for loops ? (I am very new to Python)

DSM
  • 342,061
  • 65
  • 592
  • 494

2 Answers2

6

You can use zip (itertools.izip if the lists are large):

>>> x = ['a','b','c']
>>> y = ['d','e','f']
>>> zip(x, y)
[('a', 'd'), ('b', 'e'), ('c', 'f')]
>>> map(list, zip(x, y))  # If you need lists instead of tuples
[['a', 'd'], ['b', 'e'], ['c', 'f']]
>>>
  • In Python 3.x, you have to convert the mapped object to a list as follows: `list(map(list, zip(x, y)))` – Ninja23 Mar 25 '21 at 09:10
1

If both the same length use enumerate:

[[a,y[ind]] for ind, a in enumerate(x)]

It is more efficient than zip.

In [6]: %timeit [[a,y[ind]] for ind,a in enumerate(x)]
1000000 loops, best of 3: 970 ns per loop

In [7]: %timeit map(list, zip(x, y))
1000000 loops, best of 3: 1.48 µs per loop
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321