-1

I have two lists that I've created using import random, so their elements and lengths are random. My aim is to get every first, second, third, etc. from these lists. For example, these are my two list outputs.

My list length is 4
List1 (Original List):   [62, 51, 66, 57]
List 2 (Sum of neighbors of List 1):   [113, 179, 174, 123]

My aim is to get,

List3: [62, 113, 51, 179, 66, 174, 57, 123]

This is my only attempt but it is completely incorrect.

def order(list1, list2):
list3=[]
result_num = []
for i in range(len(list1)):
    result_num.extend(list1[i::3])
return result_num
result = order(list1)

Is it possible to write this program without any third party library? Any help would be appreciated!

  • Does this answer your question? [Interleave multiple lists of the same length in Python](https://stackoverflow.com/questions/7946798/interleave-multiple-lists-of-the-same-length-in-python) – Joe Dec 26 '20 at 10:53

3 Answers3

2

You could also use a list comprehension:

list1 = [62, 51, 66, 57]
list2 = [113, 179, 174, 123]

list3 = [value for pair in zip(list1, list2) for value in pair]

print(list3)
# [62, 113, 51, 179, 66, 174, 57, 123]

(As a side note, I removed the capital from the names of your lists - the convention in Python is to use capitalized names for classes only)

Thierry Lathuille
  • 23,663
  • 10
  • 44
  • 50
0

Yes, you can zip two lists up:

def order(list1, list2):
    result_num = []
    for i,j in zip(list1, list2):
        result_num.append(i)
        result_num.append(j)
    return result_num

print(order([62, 51, 66, 57], [113, 179, 174, 123]))

Output as requested

Update:

Using random for length and contents of lists:

random.seed()
len1 = random.randrange(4,10)
len2 = random.randrange(4,10)
l1 = [random.randrange(1,100) for _ in range(len1)]
l2 = [random.randrange(1,100) for _ in range(len2)]

print(l1)
print(l2)
print(order(l1,l2))

Sample output:

[60, 46, 11, 60, 88, 63, 93, 17]
[74, 25, 45, 67, 20]
[60, 74, 46, 25, 11, 45, 60, 67, 88, 20]
quamrana
  • 37,849
  • 12
  • 53
  • 71
  • I am getting error. –  Dec 09 '20 at 18:07
  • How can you be getting the same error for all of these different answers? Did you copy my code and run it? – quamrana Dec 09 '20 at 19:40
  • Yes, I think the problem is, as I mentioned in my questiın my lists are random so my given lists are examples, it changes every time. Instead, you used like they are stable. –  Dec 09 '20 at 19:45
  • Ok, I'll generate some random lists and see what happens. – quamrana Dec 09 '20 at 19:54
0

I assumed (based on your example) length of your input lists are the same. Something like this should do it:

l1 = [62, 51, 66, 57]
l2 = [113, 179, 174, 123]

list_of_lists = [l1, l2]

l3 = []
for i in range(len(l1)):
    l3 += [l[i] for l in list_of_lists]
bkakilli
  • 498
  • 6
  • 12