1

Maybe I'm overthinking it but I can't think of a way to combine lists in the way I need

[1,2,3,4,5]
['A','E','I','I','U']

To result in

[[1,'A'],[2,'E'],[3,'I'],[4,'O'],[5,'U']]

If I combine them, I get tuples/rounded brackets

pee2pee
  • 3,619
  • 7
  • 52
  • 133

3 Answers3

4

You can use zip.

If you want inner lists instead of inner tuples, maybe also use map.

map(list, zip(list_1, list_2))

That will apply the list function to each tuple in the zipped up list, giving you a list of lists.

(The question specifies Python 2.7, but in Python 3, map does not return a list, so you would also have to apply the list function to the result of the map; i.e. list(map(...)) )

khelwood
  • 55,782
  • 14
  • 81
  • 108
3

If you really need a list of lists, you'll have to do the following:

>>> a = [1, 2, 3, 4, 5]
>>> b = ['a', 'b', 'c', 'd', 'e']
>>> result = [list(zipped) for zipped in zip(a, b)]
>>> result
[[1, 'a'], [2, 'b'], [3, 'c'], [4, 'd'], [5, 'e']]
leovp
  • 4,528
  • 1
  • 20
  • 24
0

This is what zip is for

list_a = [1,2,3,4,5]
list_b = ['A','E','I','I','U']

list_res = zip(list_a, list_b)        # Python 2.7
list_res = list(zip(list_a, list_b))  # Python 3 onward

If you indeed want the inner containers to be tuples, then you can use map as @khelwood proposed or a list-comprehension, or an explicit loop, or...

list_of_lists = map(list, list_res)        # Python 2.7
list_of_lists = list(map(list, list_res))  # Python 3 onward

Note the similar behavior of map and zip on the two Python versions. On python 2 they returned lists whereas on Python 3 they return iterators.

Ma0
  • 15,057
  • 4
  • 35
  • 65