Search code examples
pythonpython-3.xlistnumbers

combining a new list with two base lists


I would like to combine two lists by organizing them in a way where the first element of the first is the first item of the new list and the first element of the second is the second element of the new list and so on

count = 12
list = list(range(count))

list1 = []
list2 = []

for x in range(0, count, 4):
    list1.append(x)

for y in range(3, count, 4):
    list2.append(y)

#Concatenate doesn't work
newlist = list1 + list2

print(newlist)
print(list)

The result of this is:

newlist = [0, 4, 8, 3, 7, 11]

But I want something like this:

newlist = [0, 3, 4, 7, 8, 11]

Solution

  • You can use sorted to archieve your result

    count = 12
    list = list(range(count))
    
    list1 = []
    list2 = []
    
    for x in range(0, count, 4):
        list1.append(x)
    
    for y in range(3, count, 4):
        list2.append(y)
    
    print(list1)# ==> [0, 4, 8]
    print(list2)# ==> [3, 7, 11]
    newlist = list1 + list2
    print(sorted(newlist))# ==> [0, 3, 4, 7, 8, 11]