Count the elements before a certain index in a list in Python

Viewed 38

Here is a demo list. It is a list of strings:

list_one = ['3', '5', '6', 'Week 1', '11', '12', '13', 'Week 2', '279']

Here is my code:

counts = []
for num, i in enumerate(list_one):
    if "Week" in i:
        counts.append(num)
        num = 0
        
print(counts)

Instead of the output [3, 7], I'd like to get [3, 3]

I don't want to count any element that has already been counted and to exclude countings weeks themselves. In my head, I'm imagining resetting the num back to 0 after every occurrence of 'Week' in order to accomplish this but it isn't working.

3 Answers
list_one = ['3', '5', '6', 'Week 1', '11', '12', '13', 'Week 2', '279']
count = 0
counts = []
for element in list_one:
    if "Week" in element:
        counts.append(count)
        count = 0
    else:
        count += 1
print(counts)

The last variable is used as a "floating base" to calculate the relative index

list_one = ['3', '5', '6', 'Week 1', '11', '12', '13', 'Week 2', '279']
counts, last = [], -1
for num, i in enumerate(list_one):
    if "Week" in i:
        counts.append(num - last - 1)
        last = num

print(counts)
[3, 3]

The enumarate actually gives

[(0, '3') (1, '5') (2, '6') (3, 'Week 1') (4, '11') (5, '12') (6, '13') (7, 'Week 2') (8, '279')]

when you make num to 0 in the iteration, it only applies for present iteration. It changes in next iteration

list_one = ['3', '5', '6', 'Week 1', '11', '12', '13', 'Week 2', '279']
counts = []
num = 0
for i in list_one:
    if "Week" in i:
        counts.append(num)
        num = 0
    else:
        num += 1
print(counts)

check the above code

Related