[Tutor] Getting range of a list

Steven D'Aprano steve at pearwood.info
Tue Feb 5 22:28:47 CET 2013


On 06/02/13 08:08, Hs Hs wrote:

> Here is what I do :
>>>> f1 = open('test','r')
>>>> da = f1.read().split('\n')
>>>> dat = da[:-1]
>>>> dat
>>>> mpos = []
>
>>>> for i in range(len(dat)):
> if dat[i].startswith('>'):
> mpos.append(i)
>
>>>> mpos
> [0, 3, 6, 9]
>
>>>> for item in range(len(mpos)):
> start = mpos[item]
> enda = item+1
> end  = mpos[enda]-1
> head = dat[start]
> block  = dat[start+1:end]
> for i in block:
> print head+'\t'+i


You are thinking like a C programmer, not a Python programmer. You should almost never need to iterate over a range of numbers like this.

Instead, try something like this:

f = open('test')
head = '----'
for line in f:
     if line.startswith('>'):
         head = line[1:].rstrip()  # remove trailing newline
     else:
         print head + '\t' + line

f.close()



In general, you should iterate over collections of data directly. For example:

# WRONG
for i in range(len(data)):
     x = data[i]
     print x

# RIGHT
for x in data:
     print x



# WRONG
for i in range(len(data)):
     x = data[i]
     if x == 'spam':
         data[i] = 'ham'

# RIGHT
for i, x in enumerate(data):
     if x == 'spam':
         data[i] = 'ham'



Hope this helps.



-- 
Steven


More information about the Tutor mailing list