How can you produce the following list with range()
in Python?
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
Join Stack Overflow to learn, share knowledge, and build your career.
use reversed()
function:
reversed(range(10))
It's much more meaningful.
Update:
If you want it to be a list (as btk pointed out):
list(reversed(range(10)))
Update:
If you want to use only range
to achieve the same result, you can use all its parameters. range(start, stop, step)
For example, to generate a list [5,4,3,2,1,0]
, you can use the following:
range(5, -1, -1)
It may be less intuitive but as the comments mention, this is more efficient and the right usage of range for reversed list.
range(10)
, not range(9)
. Also, if you want a fully-formed list (for slicing, etc.), you should do list(reversed(range(10)))
.
– John Y
Sep 2 '11 at 16:49
reversed
does not accept generators in general but it accepts range
. Why would reversed(range(10000))
need to allocate memory for the whole list? range
can return an object that implements the __reversed__
method that allows efficient reverse iteration?
– avmohan
Aug 5 '17 at 10:45
Use the 'range' built-in function. The signature is range(start, stop, step)
. This produces a sequence that yields numbers, starting with start
, and ending if stop
has been reached, excluding stop
.
>>> range(9,-1,-1)
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
>>> range(-2, 6, 2)
[-2, 0, 2, 4]
In Python 3, this produces a non-list range
object, which functions effectively like a read-only list (but uses way less memory, particularly for large ranges).
help(range)
in a python shell it will tell you the arguments. They're the number to start on, the number to end on (exclusive), and the step to take, so it starts at 9 and subtracts 1 until it gets to -1 (at which point it stops without returning, which is why the range ends at 0)
– Michael Mrozek
Sep 2 '11 at 16:24
range(start, stop, step)
-- start at the number start
, and yield results unless stop
has been reached, moving by step
each time.
– Mr. B
May 4 '15 at 21:33
You could use range(10)[::-1]
which is the same thing as range(9, -1, -1)
and arguably more readable (if you're familiar with the common sequence[::-1]
Python idiom).
For those who are interested in the "efficiency" of the options collected so far...
Jaime RGP's answer led me to restart my computer after timing the somewhat "challenging" solution of Jason literally following my own suggestion (via comment). To spare the curious of you the downtime, I present here my results (worst-first):
Jason's answer (maybe just an excursion into the power of list comprehension):
$ python -m timeit "[9-i for i in range(10)]"
1000000 loops, best of 3: 1.54 usec per loop
martineau's answer (readable if you are familiar with the extended slices syntax):
$ python -m timeit "range(10)[::-1]"
1000000 loops, best of 3: 0.743 usec per loop
Michał Šrajer's answer (the accepted one, very readable):
$ python -m timeit "reversed(range(10))"
1000000 loops, best of 3: 0.538 usec per loop
bene's answer (the very first, but very sketchy at that time):
$ python -m timeit "range(9,-1,-1)"
1000000 loops, best of 3: 0.401 usec per loop
The last option is easy to remember using the range(n-1,-1,-1)
notation by Val Neekman.
for i in range(8, 0, -1)
will solve this problem. It will output 8 to 1, and -1 means a reversed list
Readibility aside, reversed(range(n))
seems to be faster than range(n)[::-1]
.
$ python -m timeit "reversed(range(1000000000))"
1000000 loops, best of 3: 0.598 usec per loop
$ python -m timeit "range(1000000000)[::-1]"
1000000 loops, best of 3: 0.945 usec per loop
Just if anyone was wondering :)
range(1000000000-1,-1,-1)
as well?
– Wolf
Jun 13 '17 at 9:51
timeit range(1000000000-1,-1,-1)
on the command line, instead see my results :-)
– Wolf
Jun 13 '17 at 11:03
reverse
because the range method can return reversed list.When you have iteration over n items and want to replace order of list returned by range(start, stop, step)
you have to use third parameter of range which identifies step
and set it to -1
, other parameters shall be adjusted accordingly:
-1
(it's previous value of stop - 1
, stop
was equal to 0
).n-1
.So equivalent of range(n) in reverse order would be:
n = 10
print range(n-1,-1,-1)
#[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
The requirement in this question calls for a list
of integers of size 10 in descending
order. So, let's produce a list in python.
# This meets the requirement.
# But it is a bit harder to wrap one's head around this. right?
>>> range(10-1, -1, -1)
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
# let's find something that is a bit more self-explanatory. Sounds good?
# ----------------------------------------------------
# This returns a list in ascending order.
# Opposite of what the requirement called for.
>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# This returns an iterator in descending order.
# Doesn't meet the requirement as it is not a list.
>>> reversed(range(10))
<listreverseiterator object at 0x10e14e090>
# This returns a list in descending order and meets the requirement
>>> list(reversed(range(10)))
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
-1
It's exactly this pattern that makes it easy to keep wrap one's head around this
-- Today I learned that if it really has to be efficient, use range(n-1, -1, -1)
when traversing a range in reversed order.
– Wolf
Jun 13 '17 at 11:09
You can do printing of reverse numbers with range() BIF Like ,
for number in range ( 10 , 0 , -1 ) :
print ( number )
Output will be [10,9,8,7,6,5,4,3,2,1]
range() - range ( start , end , increment/decrement ) where start is inclusive , end is exclusive and increment can be any numbers and behaves like step
Very often asked question is whether range(9, -1, -1)
better than reversed(range(10))
in Python 3? People who have worked in other languages with iterators immediately tend to think that reversed() must cache all values and then return in reverse order. Thing is that Python's reversed()
operator doesn't work if the object is just an iterator. The object must have one of below two for reversed() to work:
len()
and integer indexes via []
__reversed__()
method implemented.If you try to use reversed() on object that has none of above then you will get:
>>> [reversed((x for x in range(10)))]
TypeError: 'generator' object is not reversible
So in short, Python's reversed()
is only meant on array like objects and so it should have same performance as forward iteration.
But what about range()
? Isn't that a generator? In Python 3 it is generator but wrapped in a class that implements both of above. So range(100000)
doesn't take up lot of memory but it still supports efficient indexing and reversing.
So in summary, you can use reversed(range(10))
without any hit on performance.
range(9,-1,-1)
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
reversed(range(10))
is less error-prone. No offence Asinox. Just an honest observation.
– Michał Šrajer
May 21 '13 at 16:47
Using without [::-1] or reversed -
def reverse(text):
result = []
for index in range(len(text)-1,-1,-1):
c = text[index]
result.append(c)
return ''.join(result)
print reverse("python!")
i believe this can help,
range(5)[::-1]
below is Usage:
for i in range(5)[::-1]:
print i
I thought that many (as myself) could be more interested in a common case of traversing an existing list in reversed order instead, as it's stated in the title, rather than just generating indices for such traversal.
Even though, all the right answers are still perfectly fine for this case, I want to point out that the performance comparison done in Wolf's answer is for generating indices only. So I've made similar benchmark for traversing an existing list in reversed order.
TL;DR a[::-1]
is the fastest.
NB: If you want more detailed analysis of different reversal alternatives and their performance, check out this great answer.
Prerequisites:
a = list(range(10))
%timeit [a[9-i] for i in range(10)]
1.27 µs ± 61.5 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
%timeit a[::-1]
135 ns ± 4.07 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
%timeit list(reversed(a))
374 ns ± 9.87 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
%timeit [a[i] for i in range(9, -1, -1)]
1.09 µs ± 11.1 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
As you see, in this case there's no need to explicitly generate indices, so the fastest method is the one that makes less extra actions.
NB: I tested in JupyterLab which has handy "magic command" %timeit
. It uses standard timeit.timeit
under the hood. Tested for Python 3.7.3
a[:: - 1]
turned out to be the fastest because you only counted the reversal time. If you write fairly: * Janson's answer: %timeit [9-i for i in range (10)]
* martineau's answer: %timeit list(range(10)) [:: - 1]
* Michał Šrajer's answer: %timeit list(reversed(range(10)))
* bene's answer: %timeit list(range(9, -1, -1))
Each of these solutions will give you a list. And the fastest solution, as @Wolf showed, is bene's answer => range (9, -1, -1)
– Szczerski
Dec 7 '20 at 15:16
a = [3, 4, 100, 1, 20, -10, 0, 9, 5, 4]
in prerequisites. It brakes your code, but not mine. My answer is for the case when the arbitrary list is already given
– pkuderov
Dec 8 '20 at 10:26
a = [3, 4, 100, 1, 20, -10, 0, 9, 5, 4]
then use reverse()
instead of [:: - 1]
. a.reverse ()
is twice as fast.
– Szczerski
Dec 9 '20 at 11:45
a = [0..9]
scenario. Timings from the popular answer may be misleading for more general cases. I needed timings for myself, so I did and shared them here. I didn't want in-place reversal - I needed just a plain list with a copy of the origin list in reverse order. Of course, this test is greatly simplified, and results may/should vary for a bit different test alternatives.
– pkuderov
Dec 11 '20 at 2:46
You don't necessarily need to use the range function, you can simply do list[::-1] which should return the list in reversed order swiftly, without using any additions.
Suppose you have a list call it a={1,2,3,4,5} Now if you want to print the list in reverse then simply use the following code.
a.reverse
for i in a:
print(i)
I know you asked using range but its already answered.
range(9,-1,-1)
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
Is the correct form. If you use
reversed(range(10))
you wont get a 0 case. For instance, say your 10 isn't a magic number and a variable you're using to lookup start from reverse. If your n case is 0, reversed(range(0)) will not execute which is wrong if you by chance have a single object in the zero index.
because range(n)
produces an iterable there are all sorts of nice things you can do which will produce the result you desire, such as:
range(n)[::-1]
if loops are ok, we can make sort of a queue:
a = []
for i in range(n):
a.insert(0,a)
return a
or maybe use the reverse() method on it:
reverse(range(n))