+ 1

How to combine lists as given in the example?

Example: list_1 = ["apple", "banana", "orange"] list_2 = ["spam", "eggs", "beef"] is it possible for the output to end up like this: ["apple", "spam", "banana", "eggs", "orange", "beef"] or maybe even randomize its position?

28th May 2020, 3:12 AM
Marwan
7 Antworten
+ 4
Numpy is useful here: import numpy as np print(np.array([i for i in list(zip(list_1, list_2))]).ravel()) If you want without numpy use this: f̶̶̶o̶̶̶r̶̶̶ ̶̶̶i̶̶̶,̶̶̶ ̶̶̶v̶̶̶ ̶̶̶i̶̶̶n̶̶̶ ̶̶̶l̶̶̶i̶̶̶s̶̶̶t̶̶̶(̶̶̶z̶̶̶i̶̶̶p̶̶̶(̶̶̶r̶̶̶a̶̶̶n̶̶̶g̶̶̶e̶̶̶(̶̶̶1̶̶̶,̶̶̶ ̶̶̶6̶̶̶,̶̶̶ ̶̶̶2̶̶̶)̶̶̶,̶̶̶ ̶̶̶l̶̶̶i̶̶̶s̶̶̶t̶̶̶_̶̶̶2̶̶̶)̶̶̶)̶̶̶:̶ ̶l̶̶̶i̶̶̶s̶̶̶t̶̶̶_̶̶̶1̶̶̶.̶̶̶i̶̶̶n̶̶̶s̶̶̶e̶̶̶r̶̶̶t̶̶̶(̶̶̶i̶̶̶n̶̶̶t̶̶̶(̶̶̶i̶̶̶)̶̶̶,̶̶̶ ̶̶̶v̶̶̶)̶̶̶ ̶̶̶p̶̶̶r̶̶̶i̶̶̶n̶̶̶t̶̶̶(̶̶̶l̶̶̶i̶̶̶s̶̶̶t̶̶̶_̶̶̶1̶̶̶)̶̶̶ I suggest you to go for Ipang 's method
28th May 2020, 5:11 AM
Valmob101
Valmob101 - avatar
+ 4
list_1 = ["apple", "banana", "orange"] list_2 = ["spam", "eggs", "beef"] # extend() works list_combined = [] for x, y in zip(list_1, list_2): list_combined.extend((x, y)) print(list_combined) # append() also works list_combined = [] for x, y in zip(list_1, list_2): list_combined.append(x) list_combined.append(y) print(list_combined) You can also shuffle <list_1> and <list_2> before extending or appending to <list_combined>.
28th May 2020, 6:14 AM
Ipang
+ 1
list_1 = ["apple", "banana", "orange"] list_2 = ["spam", "eggs", "beef"] tl = list() for x in zip(list_1, list_2 ): tl.extend(x) print(tl)
28th May 2020, 8:06 AM
$¢𝐎₹𝔭!𝐨𝓝
$¢𝐎₹𝔭!𝐨𝓝 - avatar
0
Easily adding both list as👇👇 list3=list1+list2 print(list3)
28th May 2020, 2:07 PM
Sâñtôsh
Sâñtôsh - avatar
0
List1.extend(list2) With the method extend you don't need to loop in the list. Extend deconstfucts an iterable and adds its elements to the list.
30th May 2020, 12:01 AM
GeraltdeRivia