Alison
Alison

Reputation: 3

'list index out of range' error when appending to a list

I'm trying to iterate through a list (A) to create another list (B). If the entry in the list A is the same as the previous entry in list A, I want to append list B with the same value from the previous entry in list B. If the entry in list A is not the same, I'd like to increment the count in list B. For example, for

list A = ['2014-06-01', '2014-06-01', '2014-06-02', '2014-06-03', '2014-06-03', '2014-06-03'] 

I would want

list B = [0, 0, 1, 2, 2, 2]

I'm getting an 'list index out of range' error and I can't understand why.

list_of_dates = ['2014-06-01', '2014-06-01', '2014-06-02', '2014-06-03', '2014-06-03', '2014-06-03']

case_day_count = [0]
for i in xrange(1,len(list_of_dates)): 
    if i == 1:
        continue
    if list_of_dates[i] == list_of_dates[(i-1)]:
        case_day_count.append(case_day_count[(i-1)])
    else:
        case_day_count.append(case_day_count[(i-1)]+1)

Upvotes: 0

Views: 168

Answers (3)

roh
roh

Reputation: 11

I think you did a little mistake here you should remove the first if statement:

if i == 1:
        continue

I have removed it and got the expected result just as you wanted.

remember that list index starts with 0. your statement says "skip the second element (index 1)". while you actually want to skip the first element (index 0).

since you are starting with second element (index 1), you do not need this if statement.

Upvotes: 0

jedwards
jedwards

Reputation: 30210

You could use something like:

import itertools
list_of_dates = ['2014-06-01', '2014-06-01', '2014-06-02',
                 '2014-06-03', '2014-06-03', '2014-06-03']

case_day_count = [0]
for (a,b) in itertools.izip(list_of_dates[:-1], list_of_dates[1:]):
    case_day_count.append(case_day_count[-1] + int(a != b))

print(case_day_count)

But it might not really be clear what's going on here. Instead, this may be a better compromise:

import itertools
list_of_dates = ['2014-06-01', '2014-06-01', '2014-06-02',
                 '2014-06-03', '2014-06-03', '2014-06-03']

case_day_count = [0]
for (a,b) in itertools.izip(list_of_dates[:-1], list_of_dates[1:]):
    last_count = case_day_count[-1]
    next_count = last_count + (1 if a != b else 0)
    case_day_count.append(next_count)

print(case_day_count)

Both produce [0, 0, 1, 2, 2, 2]

Upvotes: 2

Shashank
Shashank

Reputation: 13869

case_day_count has an initial length of 1 when you try to assign to case_day_count[1], which would be the 2nd element of a 1-element list, so it causes an IndexError.

If you initialize case_day_count as:

case_day_count = [0, 0]

You will get your expected list.

Upvotes: 1

Related Questions