0

Suppose we have this function:

def search(ls, e):
    '''Assumes ls is a list.
    Returns True if e is in ls, False otherwise.'''
    
    for i in reversed(range(len(ls))):
        if ls[i] == e:
            return True
    return False

I'm trying to get this function to search through ls starting from the end of the list instead of the beginning. Hence, I included reversed(), which reverses the list, ls.

However, what I'm specifically trying to do is search a list but instead of starting from the index of 0, starting from the index of -1. I don't think reversed() technically does this? If not, how could the function be modified to achieve my objective?

HelpMe
  • 87
  • 1
  • 8
  • Does this answer your question? [Traverse a list in reverse order in Python](https://stackoverflow.com/questions/529424/traverse-a-list-in-reverse-order-in-python) – Chris Dec 04 '20 at 21:22
  • Is it correct? Yes. Is it efficient? There are better ways of doing it. E.g.: `for i in range(len(ls) - 1, -1, -1):`. – kaveh Dec 04 '20 at 21:26
  • @kaveh could you explain what the `-1, -1, -1` parts do please? – HelpMe Dec 04 '20 at 21:31
  • @HelpMe range can accept 3 args, start, stop, and step. You can have reverse range by specifying a negative step. So in the case above, start is `len(ls) -1`, stop is -1 (because it's exclusive), and step is -1. Check out `range` docs for more info: https://docs.python.org/3.8/library/stdtypes.html?highlight=range#range – kaveh Dec 04 '20 at 21:45
  • @kaveh thank you! Is there a reason why it wouldn't be `-1, 0, -1`? Because then if you start at -1, would 0 mean that it would stop searching through the list when it reaches the first element at index 0? That's what we want here, no? – HelpMe Dec 05 '20 at 13:59

3 Answers3

1
list1 = [1,2,3,4,5]
for i in reversed(range(len(list1))):
    print(list1[i])

5
4
3
2
1

it does exactly what you want no?

l2 = [1,2,3,4,5]

for i in range(len(l2)):
    print(l2[-i-1])

5
4
3
2
1
ombk
  • 2,036
  • 1
  • 4
  • 16
  • In terms of the output, yes. In terms of what I want, not quite. As far as I understand, it reverses the list, then searches from the start (index 0) of that reversed list. I'm trying to get the function to start from the end of a list, i.e. index -1. Does this make sense? @ombk – HelpMe Dec 04 '20 at 21:33
  • how is what you're saying making any sense? if the list is searched from its last index then it is searched reverse wise. just print out the list you're providing and you'll see it yourself – ombk Dec 04 '20 at 21:34
  • Oh, does this mean that the list when modified with `reversed()` means that the list elements keep their original index value? – HelpMe Dec 04 '20 at 21:46
  • `len(list1) = 5` , `i in range(5)` is `1,2,3,4,5` ... `i in reversed(range(5))` is `5,4,3,2,1` – ombk Dec 04 '20 at 21:48
  • Yes, but in `range(5)`, my understanding is that index 0 is 1. In `reversed(range(5))`, is 5 now considered index 0? If so, the function doesn't search from the end of the list. It's just the list order has changed, no? I want the function to start from the end of the list, rather than have to reorder the list. – HelpMe Dec 04 '20 at 22:01
  • check my new answer and analyse it do it on a paper and pen – ombk Dec 04 '20 at 22:05
  • @HelpMe `reversed()` doesn't change the order of a list, it creates a completely new list as a copy in the reversed order. – Mark Ransom Dec 11 '20 at 20:12
0

you could try something like:

for i in range(len(ls)):
    if ls[(-1)*i] == e:
        return True
return False

It should start at the back of the list and move forward.

Andrew D.
  • 53
  • 6
0

I would actually use enumerate() to do the heavy lifting for you. Using print statements instead of return you can see how it is working better. Basically it creates a physical location index, 0 through the length of the list and allows you to iterate through both the values and the indexes. We do not need the indexes for this, but you have both.

x = [1,2,3,4,5]
for index, value in enumerate(reversed(x)):
    if value== 2:
        print("TRUE")
    else:
        print("FALSE")

This first reverses the list, creates enumerated indices and values, assigns the indices iteratively to index and each value (which can be anything a string, a float, another list)to the variable value and in the if else statement compares it to the value (which would be s in your function)

The output is:

FALSE
FALSE
FALSE
TRUE
FALSE

You can see it counted backwards toward 1. I makes seeing what is happening more explicit and allows you to use both the values and the index values of the reversed list without having to slice the original list and keep track of direction.

sconfluentus
  • 4,693
  • 1
  • 21
  • 40