-1

I want to reverse a list on Python without use reversed command. Any ideas? The query was to find another way to do the reverse the list without use any "standar" Python command like reverse. Thank in advance!

list = []
x = 1

#Import 20 random numbers
for i in range (0,20):
    list.append (x)

print (list)

for i in range (20,0,-1): # <-- I know, this is wrong. I used it as an example
    print (list[i])

SOLUTION:

list = []
    x = 1

    #Import 20 random numbers
    for i in range (0,20):
        list.append (x)

    print (list)

for i in range(len(list) - 1, -1, -1):
    print(list[i])
ulb
  • 28
  • 1
  • 13
  • Also, you should pick a different name for your list besides `list`. Currently, you are overshadowing the `list` built-in. –  Nov 26 '14 at 16:41

1 Answers1

1

You can simply use Python's slice notation to step through the list backwards:

print(list[::-1])

Demo:

>>> lst = [1, 2, 3]
>>> lst[::-1]
[3, 2, 1]
>>>

In fact, if you test this with timeit.timeit, you will see that it is a lot faster than using reversed:

>>> from timeit import timeit
>>> lst = list(range(1000))
>>> timeit('list(reversed(lst))', 'from __main__ import lst')
18.91587534169846
>>> timeit('lst[::-1]', 'from __main__ import lst')
9.677450346342901
>>>

It is also less typing. :)

Community
  • 1
  • 1
  • Is there any way to do it with for ? I think teacher want to do it with this way. Namely without use reversed, ::-1 etc. By the way, thank for your answer! – ulb Nov 26 '14 at 16:41
  • Well, I suppose you could do `for i in range(len(list) - 1, -1, -1): print(list[i])`. Note however that this an unusual and slightly unpythonic way of doing things. Using `[::-1]` or `reversed` is how most Python programmers do what you want. –  Nov 26 '14 at 16:46
  • It works! The query was to find another way to do the reverse the list without use any "standar" Python command like reverse. Thank you again! – ulb Nov 26 '14 at 18:50