0
If I have two lists then I need to make them as one list, please help me Guys
If I have two lists, I need to make them as one list by taking 1st elements of new list will the be 1st elements of the 1st list & 2 element of new list will be the 1st element of 2nd list and 2nd element of new list will be 2nd ele of 1st list and 3rd ele of new will be 2nd ele of 2nd list and and so on....
5 ответов
0
If list are same length:
l1 = [1, 1, 1]
l2 = [2, 2, 2]
l3 = []
for n in range(len(l1)):
l3.append(l1[n])
l3.append(l2[n])
print(l3)
+ 5
It is called a zip.
For two lists of equal length, you can use zip to create a zip object (an iterator over tuples, one element from one list, the second from the other).
To flatten that iterator into a list:
1)
l1 and l2 being two lists of equal length
z = [x for tup in zip(l1, l2) for x in tup]
2)
l1 and l2 as in (1)
import itertools
z = list(itertools.chain(*zip(l1, l2)))
+ 3
S GOUSE BASHA
l1 = [1, 2, 3]
l2 = [4, 5, 6]
l3 = []
for i, j in zip(l1, l2):
l3.append(i)
l3.append(j)
print (l3)
Note: in this case list should be identical
+ 2
Just another variant:
l1 = [1, 1, 1]
l2 = [2, 2, 2]
l3 = l1*2
l3[1::2]=l2
+ 1
newlist = [*list1,*list2,*list3,etc..]