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