-1

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.

martineau
  • 119,623
  • 25
  • 170
  • 301
Cory
  • 3
  • 2
  • I also want to mention, that the line `new_lst = x` is not making a copy of the list, it's only creating a second reference. If you need to make a copy, see http://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list-in-python. My preference is the `copy` package, since it's nice and explicit. – Jud Aug 09 '16 at 23:58

3 Answers3

2

You reference an item in a list by using square brackets, like so

c = new_lst[a]
d = new_lst[b]
Jud
  • 1,158
  • 1
  • 8
  • 17
0

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
senshin
  • 10,022
  • 7
  • 46
  • 59
  • Thanks all and esp thanks to @senshin ! That is exactly what I was looking for but couldn't find! – Cory Aug 10 '16 at 00:56
0

I want to return an item found at a particular index.

Do you want to use the [] operator?

new_lst[a] gets the item in new_lst at index a.

See this documentation page for more on the subject.

Bernardo Sulzbach
  • 1,293
  • 10
  • 26