rnish
rnish

Reputation: 165

max in an list within another list

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.

Upvotes: 0

Views: 109

Answers (3)

Takahiro
Takahiro

Reputation: 1262

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

Upvotes: 0

A. Rodas
A. Rodas

Reputation: 20679

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]))

Upvotes: 2

Stjepan Bakrac
Stjepan Bakrac

Reputation: 1134

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])

Upvotes: 4

Related Questions