Arrays/List, filters, Pytho, Ruby

Terry Reedy tjreedy at udel.edu
Sat Feb 12 04:49:11 CET 2011


On 2/11/2011 4:24 PM, LL.Snark wrote:
> Hi,
>
> I'm looking for a pythonic way to translate this short Ruby code :
> t=[6,7,8,6,7,9,8,4,3,6,7]
> i=t.index {|x| x<t.first}
>
> If you don't know Ruby, the second line means :
> What is the index, in array t, of the first element x such that x<t[0].

What does Ruby do if there is no such element?
For Python, the answer should be either None or ValueError.

>
> If can write it in python several ways :
> t=[6,7,8,6,7,9,8,4,3,6,7]
> i=0
> while t[i]>=t[0] : i+=1

This will raise IndexError when i gets too big.

> ... not pythonic I think...
>
> Or :
> t=[6,7,8,6,7,9,8,4,3,6,7]
> i=[j for j in range(len(t)) if t[j]<t[0]][0]

This will raise IndexError if the list is empty.

-- 
Terry Jan Reedy




More information about the Python-list mailing list