[Tutor] Weird situation in using .split() function

Kent Johnson kent37 at tds.net
Tue Nov 29 18:32:01 CET 2005


Srinivas Iyyer wrote:
> Hello group:
> 
> I have a list t and the elements are tab limited. 
> there are 2 columns:
> 
>>>>t
> 
> ['STAG2\tmiR-101', 'SMARCA1\tmiR-101',
> 'RAP2C\tmiR-101', 'DDX3Y\tmiR-101',
> 'AGRN\tmiR-101\tmiR-144', 'EPB41\tmiR-101\tmiR-144',
> 'PUM1\tmiR-101\tmiR-144',
> 'KIAA1573\tmiR-101\tmiR-144',
> 'ST6GALNAC3\tmiR-101\tmiR-144',
> 'CAPZA1\tmiR-101\tmiR-144']
> 

>>>>for i in t:
> 
> 	i = i.strip('')
> 	cols = i.split('\t')
> 	print cols[2] 	
> 
> Traceback (most recent call last):
>   File "<pyshell#527>", line 4, in -toplevel-
>     print cols[2]
> IndexError: list index out of range
 
> When I try to Print column 2 (0,1,2 which is miR-144)
> elements why is it saying index out of range whern
> miR-144 is already there. 

Because not every row has three columns, some just have two. Since the first row only has two columns it gets an error and nothing is printed. You can test for this:
	cols = i.split('\t')
	if len(cols) > 2:
		print cols[2]

Kent

-- 
http://www.kentsjohnson.com



More information about the Tutor mailing list