-3

I want to make a smaller size list around a maximum value of a big list. How can I do that efficiently using python.

tmp=[11, 22, 13, 45 ,21, 56, 26, 9, 10, 89, 77, 34, 91, 65, 67] 
max_val=max(tmp) 
max_index=tmp.index(max_val) 
print max_index,i,max_val 

In this list, the index and the maximum value and those are 13 and 91. I want a list around the index 13 of width 2 i,e [77, 34, 91, 65, 67]

Best Sudipta

tacaswell
  • 84,579
  • 22
  • 210
  • 199
user1964587
  • 519
  • 2
  • 9
  • 12
  • 2
    I haven't the slightest idea what you are talking about. Maybe if you told us how you intend to use this, or showed some code? – Robert Harvey Feb 22 '13 at 01:15
  • do you know where the maximum is? – tacaswell Feb 22 '13 at 01:15
  • 2
    Before the down voters come, I would recommend adding code that you have already tried. Remember, research your questions *before* you ask them! – xxmbabanexx Feb 22 '13 at 01:16
  • I can think of a couple ways to interpret your question. Make a single small (say 100 items) list out of the first few items of a bigger list: `smalllist = biglist[:100]`; Make many small lists containing all items of the original list: http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python/312464#312464 . Do you mean something else? You should rephrase your question. – KeJi Feb 22 '13 at 01:21

1 Answers1

1
>>> tmp = [11, 22, 13, 45 ,21, 56, 26, 9, 10, 89, 77, 34, 91, 65, 67]
>>> idx = tmp.index(max(tmp))
>>> tmp[idx-2:idx+3]
[77, 34, 91, 65, 67]
KeJi
  • 288
  • 2
  • 10
  • If i save this new list in a new variable then what will be the new index? i,e tmp1=tmp[idx-2:idx+3] then their index will be 1, 2, 3, 4, 5 instead of 11, 12, 13, 14, 15 – user1964587 Feb 22 '13 at 01:42
  • Remember that in Python, things are 0-indexed. That is, you count starting at 0. temp.index(91) → 12, so in the old list, the index of the maximum is 12, or 10, 11, 12, 13, 14 if you included the ones around it. In the new list, the indexes in the new list would be 0, 1, 2, 3, 4. – KeJi Feb 22 '13 at 01:45
  • 2
    @KeJi you should probably include checks to make sure `indx >= 2` – tacaswell Feb 22 '13 at 03:15
  • 1
    `tmp[max(0, idx-2): idx+3]` in case idx < 2 – John La Rooy Feb 22 '13 at 04:15