0

This is how the scenario looks: I am try to get the max element from an list, based on another element which essentially represents the index amongst the elements i need to search. The length of foo can change. but the length of test will not change.

>>> test = [1,2,3,4,5,6,7,8] >>> foo = [1,4] >>> print max(test[foo[1]]) 

This works..

But, when I am trying to do

>>> print max(test[foo]) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: list indices must be integers, not list 

Is there some other way, or should I refer to another module? If yes, could you please suggest it to me.

3
  • 1
    These are lists, not arrays. I'm also not clear what the goal is here, are you trying to select the maximum of item one and four, or that range, or something else? Your first example just resolves foo[1] to 4, then returns test[4], which is 5, and then gives max(5), which is 5. Commented Feb 25, 2013 at 3:12
  • 1
    At first it seems like foo represents a range, but then you say that the length of foo can change? What does that mean? Commented Feb 25, 2013 at 3:14
  • @Lattyware i'm sorry for that,i'll correct it. I'm try to get the max of the values from the test list, using the values in the list foo as an index. Am i clearer now? Commented Feb 25, 2013 at 3:22

3 Answers 3

4

Based on the other posts, I'm not sure anymore if this was what you were asking, but assuming you want the max of all the elements from test with the indices of foo (which is what I understood), you can do this:

print max([test[i] for i in foo]) 
Sign up to request clarification or add additional context in comments.

1 Comment

It appears that this is what the OP was after - note that it can be simply max(test[i] for i in foo) as a generator expression will be presumed in the context of a function call like this.
2

If foo is a list with always two elements, indicating the indices between you want to search, you can do this:

sl = slice(*foo) print(max(test[sl])) 

2 Comments

Technically, slice() will also accept one (beginning to the given point) or three parameters (start, stop, step).
Yes, I've assumed the point that has been made in one of the comments - foo represents a range, but the OP refers it as a length. Thanks for your aclaration.
0
test = [1,2,3,4,5,6,7,8] foo = [1,4] print max(test[foo[0]:foo[1]]) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.