a pythonic way of getting the range of a list that defined in the parameter?

Question:

I forced start index equant to the end index to get the whole list, but it’s not flexible enough and I wonder if there is a more intuitive/pythonic or better way of defining such function?

@click.command()
@click.option("-r", "--range", nargs=2, type=int, help="the start & end index")
def main(range):
    start, end = range
    elements = all_elements[start-1:] if start==end else all_elements[start-1:end]

EDIT: I changed the code from elements = all_elements, to the elements = all_elements[start-1:], so that when python main.py 1 100 is called, will return the first 100 items, and python main.py 5 5 returns all items from 5th.

Asked By: kay

||

Answers:

You can make your code more flexible by using a default value for the end argument. You can set it to the length of all_elements so that if only one value is provided, it will select all elements starting from that index:

@click.command()
@click.option("-r", "--range", nargs=2, type=int, help="the start & end index")
def main(range):
    start, end = range
    end = len(all_elements) if end is None else end
    elements = all_elements[start-1:end]

Alternatively, you could also provide a –all option to select all elements:

@click.command()
@click.option("-r", "--range", nargs=2, type=int, help="the start & end index")
@click.option("-a", "--all", is_flag=True, help="select all elements")
def main(range, all):
    if all:
        elements = all_elements
    else:
        start, end = range
        end = len(all_elements) if end is None else end
        elements = all_elements[start-1:end]
Answered By: rekinyz
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.