Can a for loop iterate over a list backwards?

Question

Is it possible to have a for loop iterate over a list in reverse order without changing the list?

Answer

Yes, you can iterate over a list in reverse order without changing the list using the reversed() function. In this code, the list is printed in backward order but after the for loop, the final print() shows that the original list is unchanged.

mylist = [ 1, 2, 3, 4, 5, 6, 7]

for val in reversed(mylist):
    print(val)

print(mylist)
13 Likes

Or another Answer for reversed list

k=
for i in range(len(mylist)):
k.append(mylist[len(mylist)-i-1])
print(k)

1 Like

I’d like to know more about what the computer is actually doing here. I’m a newbie to programming, but I’m guessing that for a very long list, computing the reversed list would take longer than stepping backwards through the original list. Also, in corina…'s solution, len() is called every time the for loop repeats… would the program run faster by assigning len(myList) to a variable before stepping through the list? Like this:

# an example list myList = list(range(10)) print(myList) k = [] myList_length = len(myList) for i in range(myList_length): k.append(myList[myList_length-1-i]) print(k)

I’m also wondering if there’s an interesting way to do this using a List Comprehension. Anybody?

Hi! I’m sorry to answer this a little late after your original post. I’m also a beginner in Python.

But it’s actually quite simple to do it with list comprehension!

here’s how I did it:

regular_list = list(range(10)) reversed_list = [regular_list[-elem] for elem in regular_list] print(reversed_list)

See that it could be easily read in “normal language” as “reversed_list will be equal to the [-elem] element in regular_list for EACH element in regular_list”.

Considering you’re establishing the first iteration at 0 (first element of reg list), the second will be -1, which will be assigned to the last position of reversed_list and so on (-2, -3, etc, until it reaches the end of reg list)!

(EVERYONE: I’m a newbie, so feel free to correct me if I’m wrong)

cheers!

1 Like

Close but not quite.
Positive indexes are: 0, 1, 2, 3, 4 …
Negative indexes are: -1, -2, -3, -4, -5 …
In your code you are trying to call them in the reverse order by making the positive negative, but as we can see they don’t actually line up because the positive starts on [0] and the negative starts on [-1].
Therefore you end up with the first index the same and every other index reversed but one off.
To fix this you need to shift the positive indexes down by one: regular_list[-elem - 1]

So you’d get (-0 - 1), (-1 - 1), (-2 - 1), (-3 - 1), (-4 - 1) …
Which now matches our negative indexes: -1, -2, -3, -4, -5 …

regular_list = list(range(10)) reversed_list = [regular_list[-elem] for elem in regular_list] amend_reverse = [regular_list[-elem - 1] for elem in regular_list] print(regular_list) print(reversed_list) print(amend_reverse)
2 Likes