[Tutor] Fwd: File IO help

Kent Johnson kent37 at tds.net
Fri Oct 28 15:44:01 CEST 2005

Liam Clarke wrote:
> And, a question for the group, I've always found that line[:1] is a
> complicated way of writing line[0]... is there any time when line[:1]
> != line[0]?

Actually I would say that the general case is for them to be different and in the special case where line is a string they are the same.

line[0] means, "the first element of the sequence line"
line[:1] means, "the sequence consisting of everything from the start of line up to (but not including) line[1]"

If line is a list, these two meanings are different:
 >>> r=range(4)
 >>> r
[0, 1, 2, 3]
 >>> r[0]
 >>> r[:1]

In the case of a string, line[0] is actually a sequence itself - a new string. This is kind of strange, really, that an element of a sequence can be the same as a subsequence of the sequence. It is a consequence of Python not having a character type - single characters are represented as strings.


More information about the Tutor mailing list