Get values of range object without using 'for' loop

Question:

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)])?

Asked By: LetMeSOThat4U

||

Answers:

Converting range object to list will do the job.

print(list(range(10)))

output:

 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Alternatively,

print(set(range(10)))

returns

{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
Answered By: SKY

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]
Answered By: slothrop

To convert the range values into a list you can do the following:

numbers = list(range(10)) #Get a list with values from 0 to 9
print(numbers) #Print the list
print(type(numbers)) #To see that numbers is really a list

Output:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
<class 'list'>
Answered By: Dinux
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.