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:
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.
list(map(list, zip(list1, list2)))
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)
:-)