-1

I'm struggling to define what I mean in text so as an example:

>>> list_1 = ["text text text", "text more text", "also text", "so much text"]

>>> list_2 = [0, 1, 0, 1]

>>> list_combine = some_function(list_1, list_2)

>>> print(list_combine)
[["text text text", 0],
["text more text", 1],
["also text", 0],
["so much text", 1]]

Obviously one could simply perform a loop over range(len(one of the lists)) however I'm performing this on lists with several thousand items and wondered if there was a preexisting function that did this in a quicker way? I assume Numpy likely holds the answer but I'm unsure on the search terms to find it if it does exist.

ch4rl1e97
  • 666
  • 1
  • 7
  • 24
  • Disagree with with marking this as a duplicate. That question clearly asks for tuples, I didn't. Not to mention "joining" could mean a myriad of things and the question title does not have any refining specification. – ch4rl1e97 Jan 02 '20 at 17:51

2 Answers2

1

The built-in function zip() does what you want. It produces tuples instead of lists, and you have to actually cast the resulting object to a list to get the desired output, but:

>>> list_1 = ["text text text", "text more text", "also text", "so much text"]
>>> list_2 = [0, 1, 0, 1]
>>> combined = list(zip(list_1, list_2))
>>> print(combined)
[('text text text', 0), 
 ('text more text', 1), 
 ('also text', 0), 
 ('so much text', 1)]

You could also use a list comprehension to get sublists by casting the tuples, if you really need lists instead of tuples, but that would end up being somewhat slower overall:

combined = [list(tup) for tup in zip(list1, list2)]

Note that zip() will truncate at the smallest iterable you feed it. If you want to zip bigger iterables, you can use itertools.zip_longest().

Green Cloak Guy
  • 23,793
  • 4
  • 33
  • 53
1

It is best to .zip() the lists together, and for loop through them, appending on each iteration.

list_1 = ["text text text", "text more text", "also text", "so much text"]

list_2 = [0, 1, 0, 1]
list_combine = []
for f, b in zip(list_1, list_2):
    list_combine.append((f, b))

print(list_combine)

See code snippet here

APhillips
  • 1,175
  • 9
  • 17
  • Solid answer though @Green Cloak Guy's compacted list comprehension is a little tidier I think. Personal preference of course. – ch4rl1e97 Jan 02 '20 at 17:49