1

This works fine for my purposes, except that when the value (in this case 20) is the same, it will only return the index from the front. Code is as follows, I'm not sure what the workaround is, but I need it to return the index of the value from reversed. I have some floats that would differ, but seem more difficult to work with.

lmt_lst = [-1, 5, 9, 20, 44, 37, 22, 20, 17, 12, 6, 1, -6]

lft_lmt = next(x for x in lmt_lst if x >=20)
rgt_lmt = next(x for x in reversed(lmt_lst) if x >= 20)

lft_idx = lmt_lst.index(lft_lmt)
rgt_lmt = lmt_lst.index(rgt_lmt)

print('Left Limit:', lft_lmt, 'Left Index:', lft_idx)
print('Right Limit:', rgt_lmt, 'Right Index:', rgt_idx)

If you change either of the values of '20' to 21, it works just fine

It does not return any errors, just returns the first index of the value, regardless of reversed

geodranic
  • 145
  • 9
  • Possible duplicate of [How to find all occurrences of an element in a list?](https://stackoverflow.com/questions/6294179/how-to-find-all-occurrences-of-an-element-in-a-list) – Trenton McKinney Oct 22 '19 at 05:33

1 Answers1

3

Your lft_lmt and rgt_lmt lists only contain values greater than or equal to 20, so your lists are [20, 44, 37, 22, 20] and [20, 22, 37, 44, 20] respectively.

>>> lmt_lst = [-1, 5, 9, 20, 44, 37, 22, 20, 17, 12, 6, 1, -6]
>>> [x for x in lmt_lst if x >=20]
[20, 44, 37, 22, 20]
>>> [x for x in reversed(lmt_lst) if x >= 20]
[20, 22, 37, 44, 20]

The first item of both of these lists is 20, and so when you search for them (using .index which searches from the beginning of the list) in the initial list you'll get 3 both times (because 20 is found at position 3 no matter how many times you search the list from beginning to end).

To find your right index you want to search the reversed list and account for the result being as if searching the list backwards:

>>> lft_idx = lmt_lst.index(lft_lmt)
>>> lft_idx
3
>>> rgt_idx = len(lmt_lst) - 1 - lmt_lst[::-1].index(rgt_lmt)
>>> rgt_idx
7
Nick is tired
  • 6,860
  • 20
  • 39
  • 51
  • Wow, thanks for the explanation - I spent a couple hours trying to nail it down. Well explained – geodranic Oct 22 '19 at 05:48
  • @geodranic I did miss out one part, if for example your list was `[-1, 5, 9, 44, 20, 37, 22, 20, 17, 12, 6, 1, -6]` instead (the first 20 switched with the 44) you'd still get the wrong index for your right index (you'd get 4 instead of 7) because `.index` is still returning the *first* index in the list. I thought this was clear from the emboldening of "***beginning*** of the list", hence left out. – Nick is tired Oct 22 '19 at 05:54