Search code examples
pythonfunction

Python weave lists


I want to "weave" two lists of numbers together in Python.

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

Solution

  • Python's for-loops aren't like other languages where you can have a conditional. You need to use a while loop instead or alter your for-loop:

    def weave(list1,list2):
        lijst = []
        i = 0
        while i < len(list1):
            lijst.append(list1[i])
            lijst.append(list2[i]) 
            i += 1
        return lijst
    

    I've altered your code in a variety of ways:

    • Use a while loop if you have a condition you want to loop through
    • You want the conditional to be less than the length, not less than or equal to. This is because indexing starts at 0, and if you do <=, then it will try to do list1[3] which is out of bounds.
    • Use list.append to add items to list
    • You forgot the = in i += 1
    • Finally, don't forget to return the list!

    You could also use zip():

    >>> [a for b in zip(x, y) for a in b]
    [1, 4, 2, 5, 3, 6]