Odd list behavior

E

Evan Kroske

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!

However, I can slice the list like normal, but that gives me a
one-element-long list:

key = string.split()[:1]
Success!

Finally, the operation works perfectly if I initialize the list beforehand:

list = string.split()
key = list[0]
Success!

Why does this happen?
-- |
Evan Kroske
Welcome2Obscurity.Blogspot.com <http://welcome2obscurity.blogspot.com>
Glory is fleeting, but obscurity is forever. — some French guy |
 
P

Peter Otten

Evan said:
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
Traceback (most recent call last):
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:
[]


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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,777
Messages
2,569,604
Members
45,218
Latest member
JolieDenha

Latest Threads

Top