Fwd: What's correct Python syntax?
Larry Hudson
orgnut at yahoo.com
Wed Jan 15 01:00:33 EST 2014
On 01/14/2014 02:03 AM, Igor Korot wrote:
[snip]
> C:\Documents and Settings\Igor.FORDANWORK\Desktop\winpdb>python
> Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit
> (Intel)] on win32
> Type "help", "copyright", "credits" or "license" for more information.
>>>> test = "I,like,my,chocolate"
>>>> print test.split(',')[2,3]
> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> TypeError: list indices must be integers, not tuple
>
Try again... but use a colon not a comma, [2:3]
Two additional comments:
(1) test.split(',')[2:3] will give you ["my"] only. The slicing syntax starts with the first
index and goes up to but NOT INCLUDING the second. In this case it is the same as the single
index, [2]. You want either [2:4] or [2:], or even [2:500]. Any value >= the length of the
list (or whatever sequence) is acceptable as the ending index in a slice. It's probably not a
good idea to use a value like this, but it does work. And obviously, don't try to read with an
out-of-bounds index, but it does work as the _ending_ index in a slice.
(2) A comma-separated list of data items IS a tuple, even without the usual enclosing
parenthesis. That is your error here -- [2,3] is the same as [(2,3)], which is a tuple.
-=- Larry -=-
More information about the Python-list
mailing list