Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python weave lists

I want to "weave" two numberrows together.

Example:

x = [1,2,3]
y = [4,5,6]

result = [1,4,2,5,3,6]

This is my function, I can't find out why it doesn't work:

def weave(list1,list2):
    lijst = []
    i = 0
    for i <= len(list1):
        lijst += [list1[i]] 
        lijst += [list2[i]] 
        i + 1
like image 977
Pieter Avatar asked Nov 29 '22 01:11

Pieter


1 Answers

You can use the chain function from itertools module to interleave two lists:

x = [1,2,3]
y = [4,5,6]

from itertools import chain
list(chain.from_iterable(zip(x, y)))
# [1, 4, 2, 5, 3, 6]
like image 114
Matt Avatar answered Dec 09 '22 08:12

Matt