0

For a list ["foo", "bar", "baz"] and an item in the list "bar", how do I get the index and values for the other two items only knowing that "bar" is in the list?

In other words, how do I obtain the index & value for the item before and the item after "bar"?

Paul Rooney
  • 20,879
  • 9
  • 40
  • 61
thejdah
  • 27
  • 1
  • 7
  • 1
    Do you know how to get the index for `"bar"`? If so, just subtract and add 1 to than value, respectively. – Martijn Pieters Oct 01 '18 at 23:57
  • 1
    The [`list.index`](https://docs.python.org/3.7/tutorial/datastructures.html#more-on-lists) method will tell you the index of the first instance of an entry. From this you need only add and subtract 1 from that value, then check those indices are valid (i.e. >= 0 and <= len - 1) and you are good. Then you can use the indices to get the values. – Paul Rooney Oct 01 '18 at 23:57
  • The post that was referenced when marking this as a duplicate does not have the answer to my question. Please unmark this as being a duplicate. – thejdah Oct 02 '18 at 00:06

2 Answers2

1

You can try:

L = ["foo", "bar", "baz"]
x = "bar"
ind = L.index(x)
for i in [ind-1, ind+1]:
   print(i, L[i])

which will probably output:

0 foo
2 baz

Edit Disclaimer: However, if the item you are referencing is on the end (first or last) this code will not run as you wanted it to.

Seraph Wedd
  • 864
  • 6
  • 14
0
list = ["foo","bar","foobar"]

index = list.index("bar")

a = list[index - 1]

b = list[index + 1]

print(a, b)

The .index() method will capture the index of the inserted value. In this case "bar" at index 1. When using list[index - 1] your subtracting from the bar index which would end up being 0 or "foo". Same idea when adding + 1. That will give you the index for foobar.

Kenpachi
  • 182
  • 1
  • 10
  • Well, hope you editing the answer for explaining, this needs explanation!!! – U13-Forward Oct 02 '18 at 00:01
  • Edited my answer. If you'd like more detail just ask. – Kenpachi Oct 02 '18 at 00:10
  • Ok good enough. – U13-Forward Oct 02 '18 at 00:11
  • It's not a good idea to shadow the built-in `list` type like that, even in simple example code. And your code won't work correctly if "bar" is at the start or end of the list. You should show how to handle that, or at least mention why that happens, and possible ways of dealing with it. – PM 2Ring Oct 02 '18 at 09:20