Skip over a value in the range function in python

前端 未结 7 984
我在风中等你
我在风中等你 2020-12-04 17:28

What is the pythonic way of looping through a range of numbers and skipping over one value? For example, the range is from 0 to 100 and I would like to skip 50.

Edi

相关标签:
7条回答
  • 2020-12-04 18:21

    It is time inefficient to compare each number, needlessly leading to a linear complexity. Having said that, this approach avoids any inequality checks:

    import itertools
    
    m, n = 5, 10
    for i in itertools.chain(range(m), range(m + 1, n)):
        print(i)  # skips m = 5
    

    As an aside, you woudn't want to use (*range(m), *range(m + 1, n)) even though it works because it will expand the iterables into a tuple and this is memory inefficient.


    Credit: comment by njzk2, answer by Locke

    0 讨论(0)
提交回复
热议问题