Reputation: 23
I am trying to merge two lists but I am getting an out-of-range
error:
Example:
List1 = [1,2,0,7,0]
List2 = [3,6]
For i in range(len(List1)):
if List1[i] == 0:
List1[i] = List2[i]
print(List1)
What's wrong with this code?
Upvotes: 0
Views: 142
Reputation: 49794
To replace every element of List1
that is zero, with an element of List2
,
Code:
List1 = [1, 2, 0, 7, 0]
List2 = [3, 6]
l2 = iter(List2)
List1 = [l if l != 0 else next(l2) for l in List1]
print(List1)
Produces:
[1, 2, 3, 7, 6]
Update from comments:
If List2
is possibly not long enough, one way around this is to specify a default value for next()
:
List1 = [1, 2, 0, 7, 0, 0]
List2 = [3, 6]
l2 = iter(List2)
List1 = [l if l != 0 else next(l2, None) for l in List1]
print(List1)
Which produces:
[1, 2, 3, 7, 6, None]
Upvotes: 0
Reputation: 5384
You seem to want to replace every instance of 0
from List1
with a value from List2
matching the index. The issue however is that for List1
, 0
is at index 2 (indexes start at 0) but the is no item at index 2 for List2
, hence the reason you get an IndexError
# Example
>>> lst = [1, 2, 3]
>>> lst[2]
3
>>> lst[3]
# IndexError: list index out of range
That explains what is wrong, now what would you like to do instead and maybe we can help.
Upvotes: 1