Search code examples
pythonlistiterable

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

Solution

  • 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]