Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get values of range object without using 'for' loop

It seems range() doesn’t have a method of getting values (something like dict().values()).

Is there a way of getting the values without doing "manual" iteration (like [x for x in range(10)])?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

To get a list of the values: list(range(10)) or [*range(10)]

To get a tuple: tuple(range(10))

That concise [*range(10)] solution makes use of the syntax introduced in PEP 448 ("Additional unpacking generalisations"). Generically, if itb is some finite iterable, then [*itb] is the list formed by iterating over its elements.

For example, using a generator as the iterable:

def squares_gen(n):
  for i in range(n):
    yield i**2

res = [*squares_gen(5)]
print(type(res))
print(res)

prints:

<class 'list'>
[0, 1, 4, 9, 16]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading