Cory Cory - 3 months ago 9
Python Question

Find an item in a list using the known index

I'm having trouble with Python here and need your help.

I want to return an item found at a particular index. I can't know what the item is yet, only the index. Everything I have found is the opposite of what I need, i.e., find the index of a known item using

myList.index(item)
.

Snippet:

new_lst = x
new_lst.sort()
leng = len(new_lst).....

elif leng > 1 and leng % 2 == 0:
a = (leng / 2) #or float 2.0
b = a - 1
c = new_lst.index(a) #The problem area
d = new_lst.index(b) #The problem area
med = (c + d) / 2.0
return med ......


The above will only return if
a
is in
new_lst
. Else it errors out. I want to get the middle two numbers (if list is even), add them together and then average them.

Example:
new_lst = [4,3,8,8]
. Get em, sort em, then should take the middle two numbers (
a
&
b
above, indices 1 & 2), add them and average:
(4 + 8) / 2
equaling 6. My code would assign 2 to
a
, look for it in the list and return an error: 2 not in
new_lst
. Not what I want.

Answer

You don't want the list.index function - this is for finding the position of an item in a list. To find the item at a position, you should use slicing (which, in other languages, is sometimes called "indexing", which is probably what confused you). Slicing a single element out of an iterable looks like this: lst[index].

>>> new_lst = [4, 3, 8, 8]
>>> new_lst.sort()
>>> new_lst
[3, 4, 8, 8]

>>> if len(new_lst) % 2 == 0:
    a = new_lst[len(new_lst)//2-1]
    b = new_lst[len(new_lst)//2]
    print((a+b)/2)

6.0