Loop except for certain values using Python

Question:

I am running a loop as the following:

months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'Novemeber', 'December']

for i in range(len(sections)): 

    if (' tax ' in sections[i]
    or ' Tax ' in sections[i]):

        pat=re.compile("|".join([r"b{}b".format(m) for m in months]), re.M)
        month = pat.search("n".join(sections[i].splitlines()[0:6]))
        print(month)

I want to run the loop for the values range(len(sections)) EXCEPT some of them. For example, all values covered in the range except for the values 12, 13, 55, 67 and 70.

I know I could split the range in sections but I would love to do it just by writing the numbers. Any suggestions?

Answers:

Use enumerate

for index, element in enumerate(some_list):
    if index in range(1, 20):
        print("Element: {0} with index {1} in first range".format(element, index))
    elif index in [82, 111]:
        print("Element: {0} with index {1} in second range".format(element, index))
Answered By: grzgrzgrz3

You could use the filterfalse function from itertools as follows:

from itertools import filterfalse

# Build an example list of sections, e.g. sections = [' tax 1', ' tax 2' ....., ' tax 79']
sections = [f" tax {i}" for i in range(1, 80)]

# Entries to skip over
skip = [12, 13, 55, 67, 70]

for index, value in filterfalse(lambda x : x[0] in skip, enumerate(sections, start=1)):
    print(value)

This can be used to only iterate over the required entries, skipping over the values that you do not need. It would display the following:

 tax 1
 tax 2
 tax 3
 tax 4
 tax 5
 tax 6
 tax 7
 tax 8
 tax 9
 tax 10
 tax 11
 tax 14
 tax 15
 tax 16
 tax 17
 tax 18
 tax 19
 tax 20
 tax 21
 tax 22
 tax 23
 tax 24
 tax 25
 tax 26
 tax 27
 tax 28
 tax 29
 tax 30
 tax 31
 tax 32
 tax 33
 tax 34
 tax 35
 tax 36
 tax 37
 tax 38
 tax 39
 tax 40
 tax 41
 tax 42
 tax 43
 tax 44
 tax 45
 tax 46
 tax 47
 tax 48
 tax 49
 tax 50
 tax 51
 tax 52
 tax 53
 tax 54
 tax 56
 tax 57
 tax 58
 tax 59
 tax 60
 tax 61
 tax 62
 tax 63
 tax 64
 tax 65
 tax 66
 tax 68
 tax 69
 tax 71
 tax 72
 tax 73
 tax 74
 tax 75
 tax 76
 tax 77
 tax 78
 tax 79

Or just using enumerate and in as follows:

# Build an example list of sections, e.g. sections = [' tax 1', ' tax 2' ..... ' tax 79']
sections = [f" tax {i}" for i in range(1, 80)]

for index, value in enumerate(sections, start=1):
    if index not in [12, 13, 55, 67, 70]:
        print(value)
Answered By: Martin Evans
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.