1327

How do I iterate over a list in reverse in Python?


See also: How can I get a reversed copy of a list (avoid a separate statement when chaining a method after .reverse)?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Leo.peis
  • 13,673
  • 6
  • 22
  • 20
  • Possible duplicate of https://stackoverflow.com/questions/931092/reverse-a-string-in-python – ᴇɴᴅᴇʀᴍᴀɴ Jun 24 '22 at 22:24
  • From what I can tell, the question was only ever intended to be about iteration. However, the day after it was asked, someone tried to fix the (rather poor) title - and misunderstood, giving it the title "How to reverse a list?" (which means changing around the order of the elements, **not** looking at the elements in a different order). The question then attracted answers for both problems, so now we have a rather confused canonical. I at least added to the title to indicate that both purposes are served here. – Karl Knechtel Aug 11 '22 at 08:15

37 Answers37

1646

To get a new reversed list, apply the reversed function and collect the items into a list:

>>> xs = [0, 10, 20, 40]
>>> list(reversed(xs))
[40, 20, 10, 0]

To iterate backwards through a list:

>>> xs = [0, 10, 20, 40]
>>> for x in reversed(xs):
...     print(x)
40
20
10
0
Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
codaddict
  • 445,704
  • 82
  • 492
  • 529
  • 261
    can't you just use: array[::-1] ? – kdlannoy Apr 24 '16 at 09:58
  • 177
    @kdlannoy According to the page linked to in the answer, "Compared to extended slicing, such as range(1,4)[::-1], reversed() is easier to read, runs faster, and uses substantially less memory. " – Jim Oldfield Aug 20 '16 at 15:55
  • 6
    When I tested this slicing was about twice as fast (when reversing a 10k elements list and creating a list from it). I did not test memory consumption though. `reverse` might be faster though, if you don't need to cast to list afterwards. – Dakkaron Aug 23 '16 at 14:01
  • 8
    worth noting that this is *not* the same as reverse([1,2,3]), n.b. the 'd' at the end ... which is one of the other answers below, which does this in-place, whereas this returns an iterator. – Luciano Oct 08 '16 at 09:36
  • 24
    Why use `reversed()` instead of slicing? Read the Zen of Python, rule number 7: Readability counts! – kramer65 Apr 25 '17 at 08:26
  • 2
    The list versus iterator note at the bottom of this answer is really important to emphasize to python novices (like me!) as it caught me out badly when I used a reversed list in a loop and did not know about the single use only behaviour of an iterator (see https://stackoverflow.com/questions/25336726/why-cant-i-iterate-twice-over-the-same-data) – ClimateUnboxed Aug 09 '19 at 16:16
  • One more point with `reversed` you can't do like `l = [1,2,3]; b = l+reversed(l)` which cause `TypeError: can only concatenate list (not "list_reverseiterator") to list`, but you can `b = l+l[::-1]`. Update: you can do it like: `b = l+list(reversed(l))` – mrgloom Sep 18 '19 at 15:43
  • 1
    In my opinion, `reversed()` is best for readability, `[::-1]` yields a list object (which is what we want - why yield a `list_reverseiterator` instead? you'd think most would want a reversed list here), and `.reverse()` only works in-place. – Vainmonde De Courtenay May 18 '21 at 13:37
1503
>>> xs = [0, 10, 20, 40]
>>> xs[::-1]
[40, 20, 10, 0]

Extended slice syntax is explained here. See also, documentation.

Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
mechanical_meat
  • 163,903
  • 24
  • 228
  • 223
  • Out of curiosity, what benefits (if any) does this have over list.reverse()? – Tim Oct 15 '10 at 07:03
  • 14
    It works for any interable, not just lists. Disadvantage is that it's not in place. – Swiss Oct 15 '10 at 07:04
  • 7
    @Tim it returns a slice, so doesn't change the actual list contents – fortran Oct 15 '10 at 07:04
  • 3
    @Swiss Not in every iterable, for example, `set` is iterable, but not subscriptable. – fortran Oct 15 '10 at 07:06
  • 12
    @lunixbochs reversed returns an iterator and not a list in Python 3. – Swiss Oct 15 '10 at 07:09
  • What's with the link to a super-old version of the Python doc? – Swiss Oct 15 '10 at 07:13
  • @Swiss Python 2.3 allowed `list`, `tuple` and `str` to utilize the extended slice syntax. – Tim McNamara Oct 15 '10 at 07:56
  • 1
    This works exactly for what OP wants, but it is very hacky, in a way that you have to use exactly `L[::-1]` and it won't take value for `start, stop` as `slice` method is defined with. Try with `L[4:0:-1]` and you will see problem. – bizi Jan 28 '17 at 23:06
455

Use list.reverse to reverse a list in-place:

>>> xs = [0, 10, 20, 40]
>>> xs.reverse()
>>> xs
[40, 20, 10, 0]

Use slices to create a new list with the items in reverse order:

>>> xs[::-1]
[40, 20, 10, 0]
Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
ghostdog74
  • 327,991
  • 56
  • 259
  • 343
  • 74
    [start:stop:step] so step is -1 – papalagi Sep 26 '12 at 03:36
  • 46
    Detail: The first modifies the list in-place, the second one just returns a new reversed list, but it doesn't modify the original one. – franzlorenzon Oct 29 '13 at 14:02
  • 7
    the second example should be `L=L[::-1]` to actually reverse the list otherwise you're only returning the values in reverse – rjmoggach Sep 30 '14 at 01:53
  • let's say if i have l= [1,2,3,4,5,6] and n=2 them result must be [6,5,1,2,3,4], how can we do this – Atul Jain Jan 24 '15 at 06:56
  • you could do this: `b = l[-n:] b.reverse() l = b + l[:len(l) - n]` – Shoaib Shakeel Dec 10 '15 at 09:41
  • `List.reverse()` is better in case of additional memory limit ;) – Islam Murtazaev Jul 14 '19 at 15:57
  • Does list.reverse() use less memory? I think it must make a copy of the data while reversing as you need to use a new variable name. Compare the following L=[1,2,3].reverse() and L=[1,2,3][::-1] :-) – ClimateUnboxed Aug 09 '19 at 16:32
  • @AdrianTompkins: Umm... No. `list.reverse()` doesn't make a copy; `L=[1,2,3].reverse()` is equivalent to `L = None` but with some extra thumb twiddling before the final assignment. Like most mutating methods, it returns `None` (the implicit "Nothing to return here" marker) to make it clear it's operating in place. – ShadowRanger Jan 07 '20 at 17:56
  • Readability counts - use list.reverse() – Comrade Che Mar 26 '21 at 04:18
  • I found `pandas.cut(df, bins=lst.reverse())` did not work, while `pandas.cut(df, bins=lst[::-1])` worked... – PatrickT Dec 23 '21 at 15:32
56

Summary of Reverse Methods

There are three different built-in ways to reverse a list. Which method is best depends on whether you need to:

  1. Reverse an existing list in-place (altering the original list variable)
    • Best solution is object.reverse() method
  2. Create an iterator of the reversed list (because you are going to feed it to a for-loop, a generator, etc.)
    • Best solution is reversed(object) which creates the iterator
  3. Create a copy of the list, just in the reverse order (to preserve the original list)
    • Best solution is using slices with a -1 step size: object[::-1]

From a speed perspective, it is best to use the above built-in functions to reverse a list. For reversing, they are 2 to 8 times faster on short lists (10 items), and up to ~300+ times faster on long lists compared to a manually-created loop or generator. This makes sense - they are written in a native language (i.e. C), have experts creating them, scrutiny, and optimization. They are also less prone to defects and more likely to handle edge and corner cases.

Test Script

Put all the code snippets in this answer together to make a script that will run the different ways of reversing a list that are described below. It will time each method while running it 100,000 times. The results are shown in the last section for lists of length 2, 10, and 1000 items.

from timeit import timeit
from copy import copy

def time_str_ms(t):
    return '{0:8.2f} ms'.format(t * 1000)

Method 1: Reverse in place with obj.reverse()

If the goal is just to reverse the order of the items in an existing list, without looping over them or getting a copy to work with, use the <list>.reverse() function. Run this directly on a list object, and the order of all items will be reversed:

Note that the following will reverse the original variable that is given, even though it also returns the reversed list back. i.e. you can create a copy by using this function output. Typically, you wouldn't make a function for this, but the timing script requires it.

We test the performance of this two ways - first just reversing a list in-place (changes the original list), and then copying the list and reversing it afterward to see if that is the fastest way to create a reversed copy compared to the other methods.

def rev_in_place(mylist):
    mylist.reverse()
    return mylist

def rev_copy_reverse(mylist):
    a = copy(mylist)
    a.reverse()
    return a

Method 2: Reverse a list using slices obj[::-1]

The built-in index slicing method allows you to make a copy of part of any indexed object.

  • It does not affect the original object
  • It builds a full list, not an iterator

The generic syntax is: <object>[first_index:last_index:step]. To exploit slicing to create a simple reversed list, use: <list>[::-1]. When leaving an option empty, it sets them to defaults of the first and last element of the object (reversed if the step size is negative).

Indexing allows one to use negative numbers, which count from the end of the object's index backwards (i.e. -2 is the second to last item). When the step size is negative, it will start with the last item and index backward by that amount.

def rev_slice(mylist):
    a = mylist[::-1]
    return a

Method 3: Reverse a list with the reversed(obj) iterator function

There is a reversed(indexed_object) function:

  • This creates a reverse index iterator, not a list. Great if you are feeding it to a loop for better performance on large lists
  • This creates a copy and does not affect the original object

Test with both a raw iterator, and creating a list from the iterator.

def reversed_iterator(mylist):
    a = reversed(mylist)
    return a

def reversed_with_list(mylist):
    a = list(reversed(mylist))
    return a

Method 4: Reverse list with Custom/Manual indexing

As the timing shows, creating your own methods of indexing is a bad idea. Use the built-in methods unless you really do need to do something custom. This simply means learning the built-in methods.

That said, there is not a huge penalty with smaller list sizes, but when you scale up the penalty becomes tremendous. The code below could be optimized, I'm sure, but it can't ever match the built-in methods as they are directly implemented in a native language.

def rev_manual_pos_gen(mylist):
    max_index = len(mylist) - 1
    return [ mylist[max_index - index] for index in range(len(mylist)) ]

def rev_manual_neg_gen(mylist):
    ## index is 0 to 9, but we need -1 to -10
    return [ mylist[-index-1] for index in range(len(mylist)) ]

def rev_manual_index_loop(mylist):
    a = []
    reverse_index = len(mylist) - 1
    for index in range(len(mylist)):
        a.append(mylist[reverse_index - index])
    return a
    
def rev_manual_loop(mylist):
    a = []
    reverse_index = len(mylist)
    for index, _ in enumerate(mylist):
        reverse_index -= 1
        a.append(mylist[reverse_index])
    return a

Timing each method

Following is the rest of the script to time each method of reversing. It shows reversing in place with obj.reverse() and creating the reversed(obj) iterator are always the fastest, while using slices is the fastest way to create a copy.

It also proves not to try to create a way of doing it on your own unless you have to!

loops_to_test = 100000
number_of_items = 10
list_to_reverse = list(range(number_of_items))
if number_of_items < 15:
    print("a: {}".format(list_to_reverse))
print('Loops: {:,}'.format(loops_to_test))
# List of the functions we want to test with the timer, in print order
fcns = [rev_in_place, reversed_iterator, rev_slice, rev_copy_reverse,
        reversed_with_list, rev_manual_pos_gen, rev_manual_neg_gen,
        rev_manual_index_loop, rev_manual_loop]
max_name_string = max([ len(fcn.__name__) for fcn in fcns ])
for fcn in fcns:
    a = copy(list_to_reverse) # copy to start fresh each loop
    out_str = ' | out = {}'.format(fcn(a)) if number_of_items < 15 else ''
    # Time in ms for the given # of loops on this fcn
    time_str = time_str_ms(timeit(lambda: fcn(a), number=loops_to_test))
    # Get the output string for this function
    fcn_str = '{}(a):'.format(fcn.__name__)
    # Add the correct string length to accommodate the maximum fcn name
    format_str = '{{fx:{}s}} {{time}}{{rev}}'.format(max_name_string + 4)
    print(format_str.format(fx=fcn_str, time=time_str, rev=out_str))

Timing Results

NOTE: Below results run on Python 3.7.9

The results show that scaling works best with the built-in methods best suited for a particular type of reversing. In other words, as the object element count increases, the built-in methods outpace the other methods by even more.

The built-in method that directly achieves what you need does better than stringing things together. i.e. slicing is best if you need a copy of the reversed list - it's faster than creating a duplicate list from list(reversed(obj)) function, and faster than making a copy of the list and then doing an in-place obj.reverse(), but never by more than double the speed. Meanwhile - custom methods can take orders of magnitude longer with large lists.

For scaling, with a 1000 item list, the reversed(<list>) function call takes ~30 ms to setup the iterator, reversing in-place takes just ~55 ms, using the slice method takes ~210 ms to create a copy of the full reversed list, but the quickest manual method I made took ~8400 ms.

With 2 items in the list:

a: [0, 1]
Loops: 100,000
rev_in_place(a):             24.70 ms | out = [1, 0]
reversed_iterator(a):        30.48 ms | out = <list_reverseiterator object at 0x0000020242580408>
rev_slice(a):                31.65 ms | out = [1, 0]
rev_copy_reverse(a):         63.42 ms | out = [1, 0]
reversed_with_list(a):       48.65 ms | out = [1, 0]
rev_manual_pos_gen(a):       98.94 ms | out = [1, 0]
rev_manual_neg_gen(a):       88.11 ms | out = [1, 0]
rev_manual_index_loop(a):    87.23 ms | out = [1, 0]
rev_manual_loop(a):          79.24 ms | out = [1, 0]

With 10 items in the list:

rev_in_place(a):             23.39 ms | out = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
reversed_iterator(a):        30.23 ms | out = <list_reverseiterator object at 0x00000290A3CB0388>
rev_slice(a):                36.01 ms | out = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
rev_copy_reverse(a):         64.67 ms | out = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
reversed_with_list(a):       50.77 ms | out = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
rev_manual_pos_gen(a):      162.83 ms | out = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
rev_manual_neg_gen(a):      167.43 ms | out = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
rev_manual_index_loop(a):   152.04 ms | out = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
rev_manual_loop(a):         183.01 ms | out = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

And with 1000 items in the list:

rev_in_place(a):             56.37 ms
reversed_iterator(a):        30.47 ms
rev_slice(a):               211.42 ms
rev_copy_reverse(a):        295.74 ms
reversed_with_list(a):      418.45 ms
rev_manual_pos_gen(a):     8410.01 ms
rev_manual_neg_gen(a):    11054.84 ms
rev_manual_index_loop(a): 10543.11 ms
rev_manual_loop(a):       15472.66 ms
LightCC
  • 9,804
  • 5
  • 52
  • 92
32

For reversing the same list use:

array.reverse()

To assign reversed list into some other list use:

newArray = array[::-1] 
fahad
  • 2,999
  • 3
  • 17
  • 20
Pawan Kumar
  • 2,132
  • 2
  • 16
  • 10
31

Using slicing, e.g. array = array[::-1], is a neat trick and very Pythonic, but a little obscure for newbies maybe. Using the reverse() method is a good way to go in day to day coding because it is easily readable.

However, if you need to reverse a list in place as in an interview question, you will likely not be able to use built in methods like these. The interviewer will be looking at how you approach the problem rather than the depth of Python knowledge, an algorithmic approach is required. The following example, using a classic swap, might be one way to do it:-

def reverse_in_place(lst):      # Declare a function
    size = len(lst)             # Get the length of the sequence
    hiindex = size - 1
    its = size/2                # Number of iterations required
    for i in xrange(0, its):    # i is the low index pointer
        temp = lst[hiindex]     # Perform a classic swap
        lst[hiindex] = lst[i]
        lst[i] = temp
        hiindex -= 1            # Decrement the high index pointer
    print "Done!"

# Now test it!!
array = [2, 5, 8, 9, 12, 19, 25, 27, 32, 60, 65, 1, 7, 24, 124, 654]

print array                    # Print the original sequence
reverse_in_place(array)        # Call the function passing the list
print array                    # Print reversed list


**The result:**
[2, 5, 8, 9, 12, 19, 25, 27, 32, 60, 65, 1, 7, 24, 124, 654]
Done!
[654, 124, 24, 7, 1, 65, 60, 32, 27, 25, 19, 12, 9, 8, 5, 2]

Note that this will not work on Tuples or string sequences, because strings and tuples are immutable, i.e., you cannot write into them to change elements.

SimonM
  • 439
  • 4
  • 7
  • 9
    The classic swap could be done via `lst[hiindex], lst[i] = lst[i], lst[hiindex]`, I think... ;-) – Samoth Mar 25 '17 at 10:50
  • @Samoth That syntax isn't as clear and the behavior isn't exactly obvious. Distinct steps make more sense. – Anthony Jul 07 '18 at 18:29
  • why people say that things like array[::-1] are pythonic? The python zen teach us that explicit is better than implicit and readability counts. Stuff like that are not explicit and readable at all. – k4ppa Aug 20 '18 at 15:36
  • 3
    @k4ppa: `array[::-1]` is perfectly readable and perfectly explicit *if you know Python*. "Readable" doesn't mean "someone who has never used Python slicing before must be able to read it"; the `[::-1]` reversing slice is a ridiculously common idiom in Python (you'll encounter it in existing code all the time), and it's perfectly readable *if you regularly use Python*. Sure, `first10 = []`, `for i in range(10): first10.append(array[i])` is clear and explicit, but that doesn't make it better than `first10 = array[:10]`. – ShadowRanger Jan 07 '20 at 18:00
  • Why is the number of iterations size/2? What's the logic behind it? Also, what if it's length isn't an even number. Then would it be ceil(size/2) – Anonymous Person Oct 30 '20 at 15:39
  • It has to be size/2 because you are working both ends of the list at the same iteration, if you used just length, you would reverse the list again back to the start point. For odd list lengths, the mid point does not have to swap – SimonM Feb 21 '21 at 16:32
  • This is one of my favourite coding challenge questions to give to a candidate, and it does not have to be python it would work equally well with Perl, bash, C#, PHP etc. There are several avenues you could pursue like is a list as a parameter passed by value or reference, do you really need to return the result if passed by reference, what would happen if you were passing a string, would it still work? Etc, – SimonM Feb 21 '21 at 16:38
22

I find (contrary to some other suggestions) that l.reverse() is by far the fastest way to reverse a long list in Python 3 and 2. I'd be interested to know if others can replicate these timings.

l[::-1] is probably slower because it copies the list prior to reversing it. Adding the list() call around the iterator made by reversed(l) must add some overhead. Of course if you want a copy of the list or an iterator then use those respective methods, but if you want to just reverse the list then l.reverse() seems to be the fastest way.

Functions

def rev_list1(l):
    return l[::-1]

def rev_list2(l):
    return list(reversed(l))

def rev_list3(l):
    l.reverse()
    return l

List

l = list(range(1000000))

Python 3.5 timings

timeit(lambda: rev_list1(l), number=1000)
# 6.48
timeit(lambda: rev_list2(l), number=1000)
# 7.13
timeit(lambda: rev_list3(l), number=1000)
# 0.44

Python 2.7 timings

timeit(lambda: rev_list1(l), number=1000)
# 6.76
timeit(lambda: rev_list2(l), number=1000)
# 9.18
timeit(lambda: rev_list3(l), number=1000)
# 0.46
Chris_Rands
  • 38,994
  • 14
  • 83
  • 119
  • 5
    `list.reverse` is the fastest, because it reverses in place – warvariuc Sep 17 '17 at 18:38
  • You're correct `list.reverse()` is fastest, but you're penalizing `reversed` (which is best used when you *don't* want a new `list`, just to iterate an existing `list` in reverse order without mutating the original), and the slice (which also avoids mutating the original `list`, and is typically faster than `reversed` when the input is small). Yes, if you don't need the copy, anything that copies is more expensive, but a lot of the time, you don't want to mutate the original value. – ShadowRanger Jan 07 '20 at 18:11
  • It looks like `reversed` [still loses to `list.reverse()`](https://tio.run/##rZHPasMwDMbvfgrdYkMWmqanlDzJGCFrlM3gP6nslJaxZ8@ULC3NBjuM6mCMvp8@SXZ/ie/eFWNH3kLUFnUEbXtPEQh7bOLYYsfXU210iLk0qhTAQRgHcmCey/IpfxHintr@ojgpWUUK2LKo1nxx4022UFKt6tf87qf/nbUQBqqlYePeUOabKbhlYLZnLZlXPXhj8BC1d@G6b4vHAfesuDBYZHJOSNucDbpqozI8R3TtHmaDuraNdnV9rTbpbb6PT2gCUCJET9pFabWT348pk8Vd0vQMSQrzVNV8Zp0ny0yuUnCDfUWqpuHT5SOqQvEW/3LcPtyxeLjj7g/HcfwC "Python 3 – Try It Online") even so, but given it doesn't mutate the input `list`, it's better in many cases. The loss for `reversed` is small (~1/6th longer than `list.reverse()`). – ShadowRanger Jan 07 '20 at 18:17
18
for x in array[::-1]:
    do stuff
Swiss
  • 5,556
  • 1
  • 28
  • 42
17

With reversed and list:

>>> list1 = [1,2,3]
>>> reversed_list = list(reversed(list1))
>>> reversed_list
>>> [3, 2, 1]
Eyal Levin
  • 16,271
  • 6
  • 66
  • 56
11
array=[0,10,20,40]
for e in reversed(array):
  print e
nonopolarity
  • 146,324
  • 131
  • 460
  • 740
8

Using reversed(array) would be the likely best route.

>>> array = [1,2,3,4]
>>> for item in reversed(array):
>>>     print item

Should you need to understand how could implement this without using the built in reversed.

def reverse(a):
    midpoint = len(a)/2
    for item in a[:midpoint]:
        otherside = (len(a) - a.index(item)) - 1
        temp = a[otherside]
        a[otherside] = a[a.index(item)]
        a[a.index(item)] = temp
    return a

This should take O(N) time.

gpj
  • 134
  • 1
  • 3
7

Another solution would be to use numpy.flip for this

import numpy as np
array = [0, 10, 20, 40]
list(np.flip(array))
[40, 20, 10, 0]
disco crazy
  • 31,313
  • 12
  • 80
  • 83
  • Great, very memorable. And unlike others solutions (shame on the OP for such a non-generic test case) it works even for unsorted lists (random numbers, etc). – mirekphd Aug 27 '21 at 15:47
4

If you want to store the elements of reversed list in some other variable, then you can use revArray = array[::-1] or revArray = list(reversed(array)).

But the first variant is slightly faster:

z = range(1000000)
startTimeTic = time.time()
y = z[::-1]
print("Time: %s s" % (time.time() - startTimeTic))

f = range(1000000)
startTimeTic = time.time()
g = list(reversed(f))
print("Time: %s s" % (time.time() - startTimeTic))

Output:

Time: 0.00489711761475 s
Time: 0.00609302520752 s
Temak
  • 2,929
  • 36
  • 49
  • 2
    Next time, you might want to use `timeit`. – grooveplex Jul 28 '16 at 08:28
  • This is a bad test for two reasons. Firstly, the fact that you only test one iteration - of something that only takes a few milliseconds to execute - means the result may be a fluke. Secondly, depending upon whether you used Python 2 or Python 3, `range(1000000)` may not be a list at all, but rather a `range` object, with its own `__reversed__` method that presumably behaves differently from that of a `list`. – Mark Amery Jul 10 '22 at 13:25
4

You can also use the bitwise complement of the array index to step through the array in reverse:

>>> array = [0, 10, 20, 40]
>>> [array[~i] for i, _ in enumerate(array)]
[40, 20, 10, 0]

Whatever you do, don't do it this way ;)

101
  • 8,514
  • 6
  • 43
  • 69
4

Using some logic

Using some old school logic to practice for interviews.

Swapping numbers front to back. Using two pointers index[0] and index[last]

def reverse(array):
    n = array
    first = 0
    last = len(array) - 1
    while first < last:
      holder = n[first]
      n[first] = n[last]
      n[last] = holder
      first += 1
      last -= 1
    return n

input -> [-1 ,1, 2, 3, 4, 5, 6]
output -> [6, 5, 4, 3, 2, 1, -1]
Heezes
  • 3
  • 3
Israel Manzo
  • 217
  • 3
  • 6
  • If we divide the list in two and swap the first with the last index and the time complexity will be more efficient than the sample listed. – Israel Manzo Jan 02 '19 at 02:17
3

Use list comprehension:

[array[n] for n in range(len(array)-1, -1, -1)]
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
koo
  • 171
  • 1
  • 11
3

ORGANIZING VALUES:

In Python, lists' order too can be manipulated with sort, organizing your variables in numerical/alphabetical order: Temporarily:

print(sorted(my_list))

Permanent:

my_list.sort(), print(my_list)

You can sort with the flag "reverse=True":

print(sorted(my_list, reverse=True))

or

my_list.sort(reverse=True), print(my_list)

WITHOUT ORGANIZING

Maybe you do not want to sort values, but only reverse the values. Then we can do it like this:

print(list(reversed(my_list)))

**Numbers have priority over alphabet in listing order. The Python values' organization is awesome.

Edit 1: a mistaken moderator claimed that my answer was a copy and deleted my old post.

Marcelo Guedes
  • 1,419
  • 11
  • 10
2

The question is not how to return a list in reverse but rather how to reverse a list with an example list name array.

To reverse a list named "array" use array.reverse().

The incredibly useful slice method as described can also be used to reverse a list in place by defining the list as a sliced modification of itself using array[:] = array[::-1].

rjmoggach
  • 1,458
  • 15
  • 27
2

With minimum amount of built-in functions, assuming it's interview settings

array = [1, 2, 3, 4, 5, 6,7, 8]
inverse = [] #create container for inverse array
length = len(array)  #to iterate later, returns 8 
counter = length - 1  #because the 8th element is on position 7 (as python starts from 0)

for i in range(length): 
   inverse.append(array[counter])
   counter -= 1
print(inverse)
Fed
  • 121
  • 1
  • 8
2

There are 3 methods to get the reversed list:

  1. Slicing Method 1: reversed_array = array[-1::-1]

  2. Slicing Method 2: reversed_array2 = array[::-1]

  3. Using the builtin function: reversed_array = array.reverse()

The third function actually reversed the list object in place. That means no copy of pristine data is maintained. This is a good approach if you don't want to maintain the old version. But doesn't seem to be a solution if you do want the pristine and reversed version.

Anuj Gupta
  • 576
  • 5
  • 9
1
def reverse(my_list):
  L = len(my_list)
  for i in range(L/2):
    my_list[i], my_list[L-i - 1] = my_list[L-i-1], my_list[i]
  return my_list
David Guyon
  • 2,759
  • 1
  • 28
  • 40
Jeff Mandell
  • 863
  • 7
  • 16
1
def reverse(text):
    output = []
    for i in range(len(text)-1, -1, -1):
        output.append(text[i])
    return output
Shawn Tsai
  • 53
  • 6
1

You could always treat the list like a stack just popping the elements off the top of the stack from the back end of the list. That way you take advantage of first in last out characteristics of a stack. Of course you are consuming the 1st array. I do like this method in that it's pretty intuitive in that you see one list being consumed from the back end while the other is being built from the front end.

>>> l = [1,2,3,4,5,6]; nl=[]
>>> while l:
        nl.append(l.pop())  
>>> print nl
[6, 5, 4, 3, 2, 1]
Rick
  • 19
  • 1
1
list_data = [1,2,3,4,5]
l = len(list_data)
i=l+1
rev_data = []
while l>0:
  j=i-l
  l-=1
  rev_data.append(list_data[-j])
print "After Rev:- %s" %rev_data 
1

The most direct translation of your requirement into Python is this for statement:

for i in xrange(len(array) - 1, -1, -1):
   print i, array[i]

This is rather cryptic but may be useful.

John Machin
  • 81,303
  • 11
  • 141
  • 189
0
>>> l = [1, 2, 3, 4, 5]
>>> print(reduce(lambda acc, x: [x] + acc, l, []))
[5, 4, 3, 2, 1]
grf
  • 29
  • 4
  • This solution is about 4.5k times slower than `l[::-1]`, and at the same time much less legible. Functional programming in Python is sadly rather slow. – Dakkaron Aug 23 '16 at 13:58
0

Reversing in-place by switching references of opposite indices:

>>> l = [1,2,3,4,5,6,7]    
>>> for i in range(len(l)//2):
...     l[i], l[-1-i] = l[-1-i], l[i]
...
>>> l
[7, 6, 5, 4, 3, 2, 1]
Julien
  • 5,243
  • 4
  • 34
  • 35
  • 1
    Works for odd length lists! –  Oct 25 '16 at 02:01
  • My solution is right! You know how python implements indexing. From right to left you have 0,1,2... and from left to right you have -1,-2,-3.. etc. To reverse a list, you cut it into two parts and you multiply the indexes on the right by their opposites on the left minus one. –  Oct 25 '16 at 18:49
0

Can be done using __reverse__ , which returns a generator.

>>> l = [1,2,3,4,5]
>>> for i in l.__reversed__():
...   print i
... 
5
4
3
2
1
>>>
SuperNova
  • 25,512
  • 7
  • 93
  • 64
0

use

print(list(reversed(list_name)))
hmn Falahi
  • 730
  • 5
  • 22
0

Reverse of a user input values in one line code:

for i in input()[::-1]: print(i,end='')
Palash Mondal
  • 468
  • 4
  • 10
0

Here's a way to lazily evaluate the reverse using a generator:

def reverse(seq):
    for x in range(len(seq), -1, -1): #Iterate through a sequence starting from -1 and increasing by -1.
        yield seq[x] #Yield a value to the generator

Now iterate through like this:

for x in reverse([1, 2, 3]):
    print(x)

If you need a list:

l = list(reverse([1, 2, 3]))
Corman
  • 749
  • 11
  • 16
-1
>>> L = [1, 2, 3, 4]
>>> L = [L[-i] for i in range(1, len(L) + 1)]
>>> L
[4, 3, 2, 1]
k15
  • 15
  • 1
-1

This class uses Python magic methods and iterators for reversing, and reverses a list:

class Reverse(object):
    """ Builds a reverse method using magic methods """

    def __init__(self, data):
        self.data = data
        self.index = len(data)


    def __iter__(self):
        return self

    def __next__(self):
        if self.index == 0:
            raise StopIteration

        self.index = self.index - 1
        return self.data[self.index]


REV_INSTANCE = Reverse([0, 10, 20, 40])

iter(REV_INSTANCE)

rev_list = []
for i in REV_INSTANCE:
    rev_list.append(i)

print(rev_list)  

Output

[40, 20, 10, 0]
Emma
  • 27,428
  • 11
  • 44
  • 69
-1

A clean simple class object to solve your issue.

class lister():
    def reverse(self):
        return  [self[len(self)-e]for e,x in enumerate(self,start=1)]
print(lister.reverse([0, 10, 20, 40]))
-1

alternative way using list comprehension and abs

array = [0, 10, 20, 40]

reversed_array = [array[abs(indx)] for indx in range(abs(len(array)-1),1)]
            
reversed_array
[40, 20, 10, 0]
vub
  • 119
  • 2
  • 3
-1
The cute Solution


class List_reverse():
    def reverse_list(self):
        list = [1, 2, 3, 4, 5, 6]
        list1 = []
        for i in range(1, len(list)+1):
            list1.append(list[-i])
        print(list1)


if __name__ == "__main__":
    obj = List_reverse()
    obj.reverse_list()
    enter code here
  • 1
    What makes this "cute", and how is it better than the 50 or so existing answers? Please read [answer], and please make sure to explain the code you share. – ChrisGPT was on strike May 19 '22 at 01:38
-2

I had this question come up during a python code test for a job interview. The below is my answer. Note it works for any value any length

def get_reverse(list_check, count_num):
    final_list =[]
    for index in range(list_length):
        value = list_check[count_num]
        final_list.append(value)
        count_num = count_num -1

    return final_list

new_list = ['A', 'GOAT', 'C', 'D', 'Mac']

list_length = len(new_list)
x = list_length -1

print(get_reverse(new_list, x))
Ryan Bowns
  • 47
  • 1
  • 2
  • There there are several points that make your function more complicated and un-pythonic than necessary – but there's a fatal error: `list_length`, which is used inside the function, exists only as a global variable. That's why I'll downvote this answer (but I'll retract the DV if you fix that). – Schmuddi Jul 07 '21 at 11:49