Simon Fraser
Simon Fraser

Reputation: 33

How to make a loop iterate from middle to beginning of a list?

I'm trying to make a loop iterate in a list from the middle of a list's index to the beginning using the for i in range() loop. How would I do that? Say we have a list

a = ['apple', 'peach', 'orange', 'melon', 'banana'] 

How would I iterate from 'orange' to 'apple'?

My prediction:

for i in range(a[orange], 0)

I'm new to programming, sorry for the obvious question.

Upvotes: 3

Views: 10099

Answers (4)

Mohamed Ramzy Helmy
Mohamed Ramzy Helmy

Reputation: 269

for x in range (len(list)/2,-1): print list[x]

Upvotes: 0

Jon Clements
Jon Clements

Reputation: 142136

You're almost there... use list.index to find the value, then reverse a slice from your list, eg:

a = ['apple', 'peach', 'orange', 'melon', 'banana']
b = a[a.index('orange')::-1]
# ['orange', 'peach', 'apple']

You'd probably want to throw in a bit of error handling for where the value isn't found in the list, eg:

try:
    b = a[a.index('not_in_list')::-1]
except ValueError:
    b = [] # or other sensible result

Then maybe a helper function:

def backwards_from(lst, value):
    try:
        return lst[lst.index(value)::-1]
    except ValueError:
        return [] # or other sensible result

for item in backwards_from(a, 'orange'):
    print item
#orange
#peach
#apple

for item in backwards_from(a, 'cabbage'):
    print item
# nothing to print

If you really, really want to use range, then you start with the index, decrementing by -1, until the start of the list (which is -1 because the end isn't included in the range), eg:

for idx in range(a.index('orange'), -1, -1):
    print a[idx]

Upvotes: 6

mgilson
mgilson

Reputation: 309841

Slicing works nicely here:

>>> a[len(a)//2::-1]
['orange', 'peach', 'apple']

So, to iterate over the objects:

>>> for fruit in a[len(a)//2::-1]:
...   print fruit
... 
orange
peach
apple

Note that len(a)//2 is the length of the list divided by 2 (truncated to an integer) and the -1 part of the slice means iterate backwards.

Upvotes: 3

Two-Bit Alchemist
Two-Bit Alchemist

Reputation: 18457

How about

for fruit in list(reversed(fruit_list))[2:]:
    print(fruit)

?

Although you can use slice notation with a negative step [::-1] to reverse an iterable, Python provides the handy and readable reversed built-in function to do the same. From there, you can just slice to the portion of the list you want.

This is also more Pythonic, since you iterate directly over the elements of the list. Generally, you don't need to keep up with the indices yourself in a for loop.

Upvotes: 0

Related Questions