Home > Software design >  Return all values from range() function and add them into an array
Return all values from range() function and add them into an array

Time:03-26

I'm trying to make a program which extracts specific PDF pages from a PDF file. To do this, I have an array where I put all page numbers I want to extract. However, to spare myself some time, I want to be able to add all pages between two page numbers (between 1 and 8 for instance).

Currently I have the following code:

def r(n1, n2):
    return range(n1, n2)

if __name__ == '__main__':
    pages_to_keep = [1, 2, 10, r(12,14)]
    print pages_to_keep

The output is:

[1, 2, 10, [12, 13]]

but what I want is:

[1, 2, 10, 12, 13, 14]

The thought here is that the r function can be called in the array to easily add multiple pages, but I want to get rid of the brackets which gets returned from the function. Is there a way to do this?

CodePudding user response:

There are two methods of doing so:

  1. pages_to_keep = [1, 2, 10] list(r(12,14))
pages_to_keep = [1, 2, 10]
pages_to_keep.extend(list(r(12,14)))

CodePudding user response:

You should use the unpacking operator (*)

pages_to_keep = [1,2,10, *list(r(12,14))]

CodePudding user response:

This is absolutely NOT advisable to do this r = range in any of your projects. Changing the name of built-in functions make the code became less legible to another developers because this will be not default in any other project.

In other words it is not pythonic and you should not do that, never!

To follow your code and to rename a function in python, just store a pointer to the function you wish, thats not necessary redefine a function for that:

r = range
r(1,2) # [1,2]

And here your answer as plain code

pages = [1,2]
pages.extend(r(5,8))

print(pages)
# [1, 2, 5, 6, 7]
  • Related