Mattpats
Mattpats

Reputation: 534

Create a list based on two other lists

What am I doing wrong? I am getting the error:

IndexError: list index out of range

I want new_col = [0,1,1,0,0,1,1,0,0,1,0,0,0,1,1,1,0,0,0,0,0]

starts = [1,5,9,13]
ends = [3,7,10,16]

new_col = []

check = 0
start_idx = 0
end_idx = 0

for i in range(20):
    if i == starts[start_idx]:
        check += 1
        new_col.append(check)
        start_idx += 1
        continue
    elif i == ends[end_idx]:
        check -= 1
        new_col.append(check)
        end_idx += 1
        continue
    else:
        new_col.append(check)
        continue

Upvotes: 1

Views: 155

Answers (2)

TimD1
TimD1

Reputation: 1032

Your problem is that start_idx and end_idx are getting incremented until they're off the end of your list.

starts = [1,5,9,13]
ends = [3,7,10,16]

should be

starts = [1,5,9,13,21]
ends = [3,7,10,16,21]

Upvotes: 0

Samwise
Samwise

Reputation: 71434

It's not clear to me exactly where the state machine is breaking, but it seems unnecessarily tricky. Rather than attempting to debug and fix it I'd just iterate over the ranges like this:

>>> starts = [1,5,9,13]
>>> ends = [3,7,10,16]
>>> new_col = [0] * 20
>>> for start, end in zip(starts, ends):
...     for i in range(start, end):
...         new_col[i] = 1
... 
>>> new_col
[0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0]

Upvotes: 3

Related Questions