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
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:
<=
, then it will try to do list1[3]
which is out of bounds.list.append
to add items to list=
in i += 1
You could also use zip()
:
>>> [a for b in zip(x, y) for a in b]
[1, 4, 2, 5, 3, 6]