Odd list behavior

Peter Otten __peter__ at web.de
Thu May 14 00:23:47 CEST 2009


Evan Kroske wrote:

> I'm working on a simple file processing utility, and I encountered a
> weird error. If I try to get the first element of a list I'm splitting
> from a string, I get an error:
> 
> key = string.split()[0]
> Error!

When string contains only whitespace string.split() returns an empty list an 
then

>>> [][0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

> However, I can slice the list like normal, but that gives me a
> one-element-long list:
> 
> key = string.split()[:1]
> Success!

The slice length may be shorter than specified:

>>> [][:1]
[]


> Finally, the operation works perfectly if I initialize the list
> beforehand:
> 
> list = string.split()
> key = list[0]
> Success!

Not with the same string as in your previous examples.

Peter




More information about the Python-list mailing list