2

I am learning python,and I am confused about how the index of an array woks in python. Following is my code

test_var = "hello how are you"

print(test_var[-1], ",", test_var.find('t'))

The output of this program is.

u , -1

Now I understand that negative indexing is allowed in python unlike java and it most probably works in cyclic manner so that -1 indicates the last character.

But when it comes to find method and it does not match any character 't' it again gives -1. So does it imply that -1 is like the null value in python? And it does not mean that find has returned the position of the last character?

Is it just me or would it be less confusing if an unsuccessful find would return None?

Lutz Prechelt
  • 36,608
  • 11
  • 63
  • 88
Pritish
  • 1,284
  • 1
  • 19
  • 42
  • The `-1` returned from `find` versus the `-1` used in indexing have completely different meanings (or semantics, you might say). The former means "item x wasn't found", the latter means "the last item in the list". These definitions are supposedly well-defined in Python documentation. If an item was found in a list, `find` will return a positive integer. Guaranteed. – TrebledJ Mar 17 '19 at 06:41

1 Answers1

0

For this example, if you index some element for an iterable (list, tuple, set or string) with negative integers, the elements start from the right to left with -1, something like this:

  0    1    2    3  
['a', 'b', 'c', 'd']
  -4  -3   -2   -1

For the find function, this return -1 when it doesn't find an element, else return the index

Geancarlo Murillo
  • 509
  • 1
  • 5
  • 14