1
votes

I want to use the join function in python (not any other function) to merge two lists into nested lists, assuming the lists are of equal length, for example:

list1 = [1, 2, 3]

list2 = ["a", "b", "c"]

I want it to produce a new list like this:

[[1,"a"], [2,"b"], [3,"c"]]
3
What "join function" are you talking about? join is not a builtin function in python2. Do you mean some module's join function? Some object's join method? - Robᵩ
Haven't tried anything? - Bleeding Fingers
Title says tuple and example expects list. How's that? - Bleeding Fingers
@Brad No, that problem is significantly different (more complicated). - user395760

3 Answers

7
votes

I don't think you understand what str.join is for.

str.join is a string method that takes an iterable (usually a list) of strings and returns a new string object that is a concatenation of those strings separated by the string that the method was invoked on.

Below is a demonstration:

>>> strs = ['a', 'b', 'c']
>>> ''.join(strs)
'abc'
>>> '--'.join(strs)
'a--b--c'
>>>

This means that you would not use str.join for what you are trying to do. Instead, you can use zip and a list comprehension:

>>> list1 = [1, 2, 3]
>>> list2 = ["a", "b", "c"]
>>> [list(x) for x in zip(list1, list2)]
[[1, 'a'], [2, 'b'], [3, 'c']]
>>>

Note however that, if you are on Python 2.x, you may want to use itertools.izip instead of zip:

>>> from itertools import izip
>>> list1 = [1, 2, 3]
>>> list2 = ["a", "b", "c"]
>>> [list(x) for x in izip(list1, list2)]
[[1, 'a'], [2, 'b'], [3, 'c']]
>>>

Like the Python 3.x zip, itertools.izip will return an iterator (instead of a list like the Python 2.x zip). This makes it more efficient, especially when dealing with larger lists.

1
votes
list(map(list, zip(list1, list2)))
0
votes

Eureka! The join function you are looking for in this context, my friend, is the following:

def join(l1, l2):
    return [list(x) for x in zip(l1, l2)]

print join(list1, list2) 

:-)