[Tutor] accessing string in list

Michiel Overtoom motoom at xs4all.nl
Tue Jul 15 20:08:05 CEST 2008

Bryan wrote...

>I have a list of labels for a data file,
>test = ['depth', '4', '6', '10', '15', '20', '30', '40', 'angle']
>If I have 15.8, I would like to get the index of '20' and '15'.  I would
>also like to make sure that my known value falls in the range 4-40.

Python has a standard module 'bisect' for that. To get past the string
trouble, you could convert the array on the fly to floats (without the first
and last label, that is). Why not build your labels as a list with numbers
first, then later add the strings at the beginning and the end?  And did you
know that lists can contain both strings and numbers at the same time?


import bisect

# simple
numbers=[4, 6, 10, 15, 20, 30, 40]
print 'insert %g before the %dth element in %s' %

# complication with strings instead of numbers:
labels=['depth', '4', '6', '10', '15', '20', '30', '40', 'angle']
if can<4 or can>40: raise ValueError('The candidate must be in the range 4-40')
position=bisect.bisect_left([float(x) for x in labels[1:-1]],can)+1
print 'insert %s before the %dth element in %s' % (candidate,position,labels)


insert 15.8 before the 4th element in [4, 6, 10, 15, 20, 30, 40]
insert 15.8 before the 5th element in ['depth', '4', '6', '10', '15', '20',
'30', '40', 'angle']


"The ability of the OSS process to collect and harness
the collective IQ of thousands of individuals across
the Internet is simply amazing." - Vinod Vallopillil

More information about the Tutor mailing list