blob: f7db94362363388fc3380a6c008083f949f8bb9a [file] [log] [blame]
Fred Drake7a2f0661998-09-10 18:25:58 +00001\section{Built-in Types \label{types}}
Fred Drake64e3b431998-07-24 13:56:11 +00002
3The following sections describe the standard types that are built into
4the interpreter. These are the numeric types, sequence types, and
Guido van Rossum77f6a652002-04-03 22:41:51 +00005several others, including types themselves.
Fred Drake64e3b431998-07-24 13:56:11 +00006\indexii{built-in}{types}
Fred Drake64e3b431998-07-24 13:56:11 +00007
8Some operations are supported by several object types; in particular,
9all objects can be compared, tested for truth value, and converted to
Fred Drake84538cd1998-11-30 21:51:25 +000010a string (with the \code{`\textrm{\ldots}`} notation). The latter
11conversion is implicitly used when an object is written by the
12\keyword{print}\stindex{print} statement.
Fred Drake64e3b431998-07-24 13:56:11 +000013
14
Fred Drake7a2f0661998-09-10 18:25:58 +000015\subsection{Truth Value Testing \label{truth}}
Fred Drake64e3b431998-07-24 13:56:11 +000016
Fred Drake84538cd1998-11-30 21:51:25 +000017Any object can be tested for truth value, for use in an \keyword{if} or
18\keyword{while} condition or as operand of the Boolean operations below.
Fred Drake64e3b431998-07-24 13:56:11 +000019The following values are considered false:
20\stindex{if}
21\stindex{while}
22\indexii{truth}{value}
23\indexii{Boolean}{operations}
24\index{false}
25
Fred Drake64e3b431998-07-24 13:56:11 +000026\begin{itemize}
27
28\item \code{None}
Fred Drake7a2f0661998-09-10 18:25:58 +000029 \withsubitem{(Built-in object)}{\ttindex{None}}
Fred Drake64e3b431998-07-24 13:56:11 +000030
Guido van Rossum77f6a652002-04-03 22:41:51 +000031\item \code{False}
32 \withsubitem{(Built-in object)}{\ttindex{False}}
33
Fred Drake38e5d272000-04-03 20:13:55 +000034\item zero of any numeric type, for example, \code{0}, \code{0L},
35 \code{0.0}, \code{0j}.
Fred Drake64e3b431998-07-24 13:56:11 +000036
Fred Drake38e5d272000-04-03 20:13:55 +000037\item any empty sequence, for example, \code{''}, \code{()}, \code{[]}.
Fred Drake64e3b431998-07-24 13:56:11 +000038
Fred Drake38e5d272000-04-03 20:13:55 +000039\item any empty mapping, for example, \code{\{\}}.
Fred Drake64e3b431998-07-24 13:56:11 +000040
41\item instances of user-defined classes, if the class defines a
Fred Drake7a2f0661998-09-10 18:25:58 +000042 \method{__nonzero__()} or \method{__len__()} method, when that
Fred Drake38e5d272000-04-03 20:13:55 +000043 method returns zero.\footnote{Additional information on these
Fred Drake66571cc2000-09-09 03:30:34 +000044special methods may be found in the \citetitle[../ref/ref.html]{Python
45Reference Manual}.}
Fred Drake64e3b431998-07-24 13:56:11 +000046
47\end{itemize}
48
49All other values are considered true --- so objects of many types are
50always true.
51\index{true}
52
53Operations and built-in functions that have a Boolean result always
Guido van Rossum77f6a652002-04-03 22:41:51 +000054return \code{0} or \code{False} for false and \code{1} or \code{True}
55for true, unless otherwise stated. (Important exception: the Boolean
56operations \samp{or}\opindex{or} and \samp{and}\opindex{and} always
57return one of their operands.)
58\index{False}
59\index{True}
Fred Drake64e3b431998-07-24 13:56:11 +000060
Fred Drake7a2f0661998-09-10 18:25:58 +000061\subsection{Boolean Operations \label{boolean}}
Fred Drake64e3b431998-07-24 13:56:11 +000062
63These are the Boolean operations, ordered by ascending priority:
64\indexii{Boolean}{operations}
65
66\begin{tableiii}{c|l|c}{code}{Operation}{Result}{Notes}
Fred Drake8c071d42001-01-26 20:48:35 +000067 \lineiii{\var{x} or \var{y}}
68 {if \var{x} is false, then \var{y}, else \var{x}}{(1)}
69 \lineiii{\var{x} and \var{y}}
70 {if \var{x} is false, then \var{x}, else \var{y}}{(1)}
Fred Drake64e3b431998-07-24 13:56:11 +000071 \hline
Fred Drake8c071d42001-01-26 20:48:35 +000072 \lineiii{not \var{x}}
Guido van Rossum77f6a652002-04-03 22:41:51 +000073 {if \var{x} is false, then \code{True}, else \code{False}}{(2)}
Fred Drake64e3b431998-07-24 13:56:11 +000074\end{tableiii}
75\opindex{and}
76\opindex{or}
77\opindex{not}
78
79\noindent
80Notes:
81
82\begin{description}
83
84\item[(1)]
85These only evaluate their second argument if needed for their outcome.
86
87\item[(2)]
Fred Drake38e5d272000-04-03 20:13:55 +000088\samp{not} has a lower priority than non-Boolean operators, so
89\code{not \var{a} == \var{b}} is interpreted as \code{not (\var{a} ==
90\var{b})}, and \code{\var{a} == not \var{b}} is a syntax error.
Fred Drake64e3b431998-07-24 13:56:11 +000091
92\end{description}
93
94
Fred Drake7a2f0661998-09-10 18:25:58 +000095\subsection{Comparisons \label{comparisons}}
Fred Drake64e3b431998-07-24 13:56:11 +000096
97Comparison operations are supported by all objects. They all have the
98same priority (which is higher than that of the Boolean operations).
Fred Drake38e5d272000-04-03 20:13:55 +000099Comparisons can be chained arbitrarily; for example, \code{\var{x} <
100\var{y} <= \var{z}} is equivalent to \code{\var{x} < \var{y} and
101\var{y} <= \var{z}}, except that \var{y} is evaluated only once (but
102in both cases \var{z} is not evaluated at all when \code{\var{x} <
103\var{y}} is found to be false).
Fred Drake64e3b431998-07-24 13:56:11 +0000104\indexii{chaining}{comparisons}
105
106This table summarizes the comparison operations:
107
108\begin{tableiii}{c|l|c}{code}{Operation}{Meaning}{Notes}
109 \lineiii{<}{strictly less than}{}
110 \lineiii{<=}{less than or equal}{}
111 \lineiii{>}{strictly greater than}{}
112 \lineiii{>=}{greater than or equal}{}
113 \lineiii{==}{equal}{}
Fred Drake64e3b431998-07-24 13:56:11 +0000114 \lineiii{!=}{not equal}{(1)}
Fred Drake512bb722000-08-18 03:12:38 +0000115 \lineiii{<>}{not equal}{(1)}
Fred Drake64e3b431998-07-24 13:56:11 +0000116 \lineiii{is}{object identity}{}
117 \lineiii{is not}{negated object identity}{}
118\end{tableiii}
119\indexii{operator}{comparison}
120\opindex{==} % XXX *All* others have funny characters < ! >
121\opindex{is}
122\opindex{is not}
123
124\noindent
125Notes:
126
127\begin{description}
128
129\item[(1)]
130\code{<>} and \code{!=} are alternate spellings for the same operator.
Fred Drake4de96c22000-08-12 03:36:23 +0000131(I couldn't choose between \ABC{} and C! :-)
Fred Drake64e3b431998-07-24 13:56:11 +0000132\index{ABC language@\ABC{} language}
Fred Drakec37b65e2001-11-28 07:26:15 +0000133\index{language!ABC@\ABC}
Fred Drake4de96c22000-08-12 03:36:23 +0000134\indexii{C}{language}
Fred Drake38e5d272000-04-03 20:13:55 +0000135\code{!=} is the preferred spelling; \code{<>} is obsolescent.
Fred Drake64e3b431998-07-24 13:56:11 +0000136
137\end{description}
138
139Objects of different types, except different numeric types, never
140compare equal; such objects are ordered consistently but arbitrarily
141(so that sorting a heterogeneous array yields a consistent result).
Fred Drake38e5d272000-04-03 20:13:55 +0000142Furthermore, some types (for example, file objects) support only a
143degenerate notion of comparison where any two objects of that type are
144unequal. Again, such objects are ordered arbitrarily but
145consistently.
146\indexii{object}{numeric}
Fred Drake64e3b431998-07-24 13:56:11 +0000147\indexii{objects}{comparing}
148
Fred Drake38e5d272000-04-03 20:13:55 +0000149Instances of a class normally compare as non-equal unless the class
150\withsubitem{(instance method)}{\ttindex{__cmp__()}}
Fred Drake66571cc2000-09-09 03:30:34 +0000151defines the \method{__cmp__()} method. Refer to the
152\citetitle[../ref/customization.html]{Python Reference Manual} for
153information on the use of this method to effect object comparisons.
Fred Drake64e3b431998-07-24 13:56:11 +0000154
Fred Drake38e5d272000-04-03 20:13:55 +0000155\strong{Implementation note:} Objects of different types except
156numbers are ordered by their type names; objects of the same types
157that don't support proper comparison are ordered by their address.
158
159Two more operations with the same syntactic priority,
160\samp{in}\opindex{in} and \samp{not in}\opindex{not in}, are supported
161only by sequence types (below).
Fred Drake64e3b431998-07-24 13:56:11 +0000162
163
Fred Drake7a2f0661998-09-10 18:25:58 +0000164\subsection{Numeric Types \label{typesnumeric}}
Fred Drake64e3b431998-07-24 13:56:11 +0000165
Guido van Rossum77f6a652002-04-03 22:41:51 +0000166There are four distinct numeric types: \dfn{plain integers},
167\dfn{long integers},
Fred Drake64e3b431998-07-24 13:56:11 +0000168\dfn{floating point numbers}, and \dfn{complex numbers}.
Guido van Rossum77f6a652002-04-03 22:41:51 +0000169In addition, Booleans are a subtype of plain integers.
Fred Drake64e3b431998-07-24 13:56:11 +0000170Plain integers (also just called \dfn{integers})
Fred Drake38e5d272000-04-03 20:13:55 +0000171are implemented using \ctype{long} in C, which gives them at least 32
Fred Drake64e3b431998-07-24 13:56:11 +0000172bits of precision. Long integers have unlimited precision. Floating
Fred Drake38e5d272000-04-03 20:13:55 +0000173point numbers are implemented using \ctype{double} in C. All bets on
Fred Drake64e3b431998-07-24 13:56:11 +0000174their precision are off unless you happen to know the machine you are
175working with.
Fred Drake0b4e25d2000-10-04 04:21:19 +0000176\obindex{numeric}
Guido van Rossum77f6a652002-04-03 22:41:51 +0000177\obindex{Boolean}
Fred Drake0b4e25d2000-10-04 04:21:19 +0000178\obindex{integer}
179\obindex{long integer}
180\obindex{floating point}
181\obindex{complex number}
Fred Drake38e5d272000-04-03 20:13:55 +0000182\indexii{C}{language}
Fred Drake64e3b431998-07-24 13:56:11 +0000183
184Complex numbers have a real and imaginary part, which are both
Fred Drake38e5d272000-04-03 20:13:55 +0000185implemented using \ctype{double} in C. To extract these parts from
Tim Peters8f01b682002-03-12 03:04:44 +0000186a complex number \var{z}, use \code{\var{z}.real} and \code{\var{z}.imag}.
Fred Drake64e3b431998-07-24 13:56:11 +0000187
188Numbers are created by numeric literals or as the result of built-in
189functions and operators. Unadorned integer literals (including hex
Fred Drake38e5d272000-04-03 20:13:55 +0000190and octal numbers) yield plain integers. Integer literals with an
191\character{L} or \character{l} suffix yield long integers
192(\character{L} is preferred because \samp{1l} looks too much like
193eleven!). Numeric literals containing a decimal point or an exponent
194sign yield floating point numbers. Appending \character{j} or
195\character{J} to a numeric literal yields a complex number.
Fred Drake64e3b431998-07-24 13:56:11 +0000196\indexii{numeric}{literals}
197\indexii{integer}{literals}
198\indexiii{long}{integer}{literals}
199\indexii{floating point}{literals}
200\indexii{complex number}{literals}
201\indexii{hexadecimal}{literals}
202\indexii{octal}{literals}
203
204Python fully supports mixed arithmetic: when a binary arithmetic
205operator has operands of different numeric types, the operand with the
206``smaller'' type is converted to that of the other, where plain
207integer is smaller than long integer is smaller than floating point is
208smaller than complex.
Fred Drakeea003fc1999-04-05 21:59:15 +0000209Comparisons between numbers of mixed type use the same rule.\footnote{
210 As a consequence, the list \code{[1, 2]} is considered equal
Fred Drake82ac24f1999-07-02 14:29:14 +0000211 to \code{[1.0, 2.0]}, and similar for tuples.
212} The functions \function{int()}, \function{long()}, \function{float()},
Fred Drake84538cd1998-11-30 21:51:25 +0000213and \function{complex()} can be used
Fred Drake64e3b431998-07-24 13:56:11 +0000214to coerce numbers to a specific type.
215\index{arithmetic}
216\bifuncindex{int}
217\bifuncindex{long}
218\bifuncindex{float}
219\bifuncindex{complex}
220
Raymond Hettinger6cf09f02002-05-21 18:19:49 +0000221All numeric types (except complex) support the following operations,
222sorted by ascending priority (operations in the same box have the same
Fred Drake64e3b431998-07-24 13:56:11 +0000223priority; all numeric operations have a higher priority than
224comparison operations):
225
226\begin{tableiii}{c|l|c}{code}{Operation}{Result}{Notes}
227 \lineiii{\var{x} + \var{y}}{sum of \var{x} and \var{y}}{}
228 \lineiii{\var{x} - \var{y}}{difference of \var{x} and \var{y}}{}
229 \hline
230 \lineiii{\var{x} * \var{y}}{product of \var{x} and \var{y}}{}
231 \lineiii{\var{x} / \var{y}}{quotient of \var{x} and \var{y}}{(1)}
Raymond Hettinger6cf09f02002-05-21 18:19:49 +0000232 \lineiii{\var{x} \%{} \var{y}}{remainder of \code{\var{x} / \var{y}}}{(4)}
Fred Drake64e3b431998-07-24 13:56:11 +0000233 \hline
234 \lineiii{-\var{x}}{\var{x} negated}{}
235 \lineiii{+\var{x}}{\var{x} unchanged}{}
236 \hline
237 \lineiii{abs(\var{x})}{absolute value or magnitude of \var{x}}{}
238 \lineiii{int(\var{x})}{\var{x} converted to integer}{(2)}
239 \lineiii{long(\var{x})}{\var{x} converted to long integer}{(2)}
240 \lineiii{float(\var{x})}{\var{x} converted to floating point}{}
241 \lineiii{complex(\var{re},\var{im})}{a complex number with real part \var{re}, imaginary part \var{im}. \var{im} defaults to zero.}{}
Fred Drake26b698f1999-02-12 18:27:31 +0000242 \lineiii{\var{c}.conjugate()}{conjugate of the complex number \var{c}}{}
Raymond Hettinger6cf09f02002-05-21 18:19:49 +0000243 \lineiii{divmod(\var{x}, \var{y})}{the pair \code{(\var{x} / \var{y}, \var{x} \%{} \var{y})}}{(3)(4)}
Fred Drake64e3b431998-07-24 13:56:11 +0000244 \lineiii{pow(\var{x}, \var{y})}{\var{x} to the power \var{y}}{}
245 \lineiii{\var{x} ** \var{y}}{\var{x} to the power \var{y}}{}
246\end{tableiii}
247\indexiii{operations on}{numeric}{types}
Fred Drake26b698f1999-02-12 18:27:31 +0000248\withsubitem{(complex number method)}{\ttindex{conjugate()}}
Fred Drake64e3b431998-07-24 13:56:11 +0000249
250\noindent
251Notes:
252\begin{description}
253
254\item[(1)]
255For (plain or long) integer division, the result is an integer.
Tim Peters8f01b682002-03-12 03:04:44 +0000256The result is always rounded towards minus infinity: 1/2 is 0,
Fred Drake38e5d272000-04-03 20:13:55 +0000257(-1)/2 is -1, 1/(-2) is -1, and (-1)/(-2) is 0. Note that the result
258is a long integer if either operand is a long integer, regardless of
259the numeric value.
Fred Drake64e3b431998-07-24 13:56:11 +0000260\indexii{integer}{division}
261\indexiii{long}{integer}{division}
262
263\item[(2)]
264Conversion from floating point to (long or plain) integer may round or
Fred Drake4de96c22000-08-12 03:36:23 +0000265truncate as in C; see functions \function{floor()} and
266\function{ceil()} in the \refmodule{math}\refbimodindex{math} module
267for well-defined conversions.
Fred Drake9474d861999-02-12 22:05:33 +0000268\withsubitem{(in module math)}{\ttindex{floor()}\ttindex{ceil()}}
Fred Drake64e3b431998-07-24 13:56:11 +0000269\indexii{numeric}{conversions}
Fred Drake4de96c22000-08-12 03:36:23 +0000270\indexii{C}{language}
Fred Drake64e3b431998-07-24 13:56:11 +0000271
272\item[(3)]
Fred Drake38e5d272000-04-03 20:13:55 +0000273See section \ref{built-in-funcs}, ``Built-in Functions,'' for a full
274description.
Fred Drake64e3b431998-07-24 13:56:11 +0000275
Raymond Hettinger6cf09f02002-05-21 18:19:49 +0000276\item[(4)]
277Complex floor division operator, modulo operator, and \function{divmod()}.
278
279\deprecated{2.3}{Instead convert to float using \function{abs()}
280if appropriate.}
281
Fred Drake64e3b431998-07-24 13:56:11 +0000282\end{description}
283% XXXJH exceptions: overflow (when? what operations?) zerodivision
284
Fred Drake4e7c2051999-02-19 15:30:25 +0000285\subsubsection{Bit-string Operations on Integer Types \label{bitstring-ops}}
Fred Drake64e3b431998-07-24 13:56:11 +0000286\nodename{Bit-string Operations}
287
288Plain and long integer types support additional operations that make
289sense only for bit-strings. Negative numbers are treated as their 2's
290complement value (for long integers, this assumes a sufficiently large
291number of bits that no overflow occurs during the operation).
292
293The priorities of the binary bit-wise operations are all lower than
294the numeric operations and higher than the comparisons; the unary
295operation \samp{\~} has the same priority as the other unary numeric
296operations (\samp{+} and \samp{-}).
297
298This table lists the bit-string operations sorted in ascending
299priority (operations in the same box have the same priority):
300
301\begin{tableiii}{c|l|c}{code}{Operation}{Result}{Notes}
302 \lineiii{\var{x} | \var{y}}{bitwise \dfn{or} of \var{x} and \var{y}}{}
303 \lineiii{\var{x} \^{} \var{y}}{bitwise \dfn{exclusive or} of \var{x} and \var{y}}{}
304 \lineiii{\var{x} \&{} \var{y}}{bitwise \dfn{and} of \var{x} and \var{y}}{}
305 \lineiii{\var{x} << \var{n}}{\var{x} shifted left by \var{n} bits}{(1), (2)}
306 \lineiii{\var{x} >> \var{n}}{\var{x} shifted right by \var{n} bits}{(1), (3)}
307 \hline
308 \lineiii{\~\var{x}}{the bits of \var{x} inverted}{}
309\end{tableiii}
310\indexiii{operations on}{integer}{types}
311\indexii{bit-string}{operations}
312\indexii{shifting}{operations}
313\indexii{masking}{operations}
314
315\noindent
316Notes:
317\begin{description}
318\item[(1)] Negative shift counts are illegal and cause a
319\exception{ValueError} to be raised.
320\item[(2)] A left shift by \var{n} bits is equivalent to
321multiplication by \code{pow(2, \var{n})} without overflow check.
322\item[(3)] A right shift by \var{n} bits is equivalent to
323division by \code{pow(2, \var{n})} without overflow check.
324\end{description}
325
326
Fred Drake93656e72001-05-02 20:18:03 +0000327\subsection{Iterator Types \label{typeiter}}
328
Fred Drakef42cc452001-05-03 04:39:10 +0000329\versionadded{2.2}
Fred Drake93656e72001-05-02 20:18:03 +0000330\index{iterator protocol}
331\index{protocol!iterator}
332\index{sequence!iteration}
333\index{container!iteration over}
334
335Python supports a concept of iteration over containers. This is
336implemented using two distinct methods; these are used to allow
337user-defined classes to support iteration. Sequences, described below
338in more detail, always support the iteration methods.
339
340One method needs to be defined for container objects to provide
341iteration support:
342
343\begin{methoddesc}[container]{__iter__}{}
Greg Ward54f65092001-07-26 21:01:21 +0000344 Return an iterator object. The object is required to support the
Fred Drake93656e72001-05-02 20:18:03 +0000345 iterator protocol described below. If a container supports
346 different types of iteration, additional methods can be provided to
347 specifically request iterators for those iteration types. (An
348 example of an object supporting multiple forms of iteration would be
349 a tree structure which supports both breadth-first and depth-first
350 traversal.) This method corresponds to the \member{tp_iter} slot of
351 the type structure for Python objects in the Python/C API.
352\end{methoddesc}
353
354The iterator objects themselves are required to support the following
355two methods, which together form the \dfn{iterator protocol}:
356
357\begin{methoddesc}[iterator]{__iter__}{}
358 Return the iterator object itself. This is required to allow both
359 containers and iterators to be used with the \keyword{for} and
360 \keyword{in} statements. This method corresponds to the
361 \member{tp_iter} slot of the type structure for Python objects in
362 the Python/C API.
363\end{methoddesc}
364
Fred Drakef42cc452001-05-03 04:39:10 +0000365\begin{methoddesc}[iterator]{next}{}
Fred Drake93656e72001-05-02 20:18:03 +0000366 Return the next item from the container. If there are no further
367 items, raise the \exception{StopIteration} exception. This method
368 corresponds to the \member{tp_iternext} slot of the type structure
369 for Python objects in the Python/C API.
370\end{methoddesc}
371
372Python defines several iterator objects to support iteration over
373general and specific sequence types, dictionaries, and other more
374specialized forms. The specific types are not important beyond their
375implementation of the iterator protocol.
376
377
Fred Drake7a2f0661998-09-10 18:25:58 +0000378\subsection{Sequence Types \label{typesseq}}
Fred Drake64e3b431998-07-24 13:56:11 +0000379
Fred Drake107b9672000-08-14 15:37:59 +0000380There are six sequence types: strings, Unicode strings, lists,
Fred Drake512bb722000-08-18 03:12:38 +0000381tuples, buffers, and xrange objects.
Fred Drake64e3b431998-07-24 13:56:11 +0000382
383Strings literals are written in single or double quotes:
Fred Drake38e5d272000-04-03 20:13:55 +0000384\code{'xyzzy'}, \code{"frobozz"}. See chapter 2 of the
Fred Drake4de96c22000-08-12 03:36:23 +0000385\citetitle[../ref/strings.html]{Python Reference Manual} for more about
386string literals. Unicode strings are much like strings, but are
387specified in the syntax using a preceeding \character{u} character:
388\code{u'abc'}, \code{u"def"}. Lists are constructed with square brackets,
Fred Drake37f15741999-11-10 16:21:37 +0000389separating items with commas: \code{[a, b, c]}. Tuples are
390constructed by the comma operator (not within square brackets), with
391or without enclosing parentheses, but an empty tuple must have the
392enclosing parentheses, e.g., \code{a, b, c} or \code{()}. A single
Guido van Rossum5fe2c132001-07-05 15:27:19 +0000393item tuple must have a trailing comma, e.g., \code{(d,)}.
Fred Drake0b4e25d2000-10-04 04:21:19 +0000394\obindex{sequence}
395\obindex{string}
396\obindex{Unicode}
Fred Drake0b4e25d2000-10-04 04:21:19 +0000397\obindex{tuple}
398\obindex{list}
Guido van Rossum5fe2c132001-07-05 15:27:19 +0000399
400Buffer objects are not directly supported by Python syntax, but can be
401created by calling the builtin function
Fred Drake4d707a52002-05-02 17:54:18 +0000402\function{buffer()}.\bifuncindex{buffer} They support concatenation
403and repetition, but the result is a new string object rather than a
404new buffer object.
Guido van Rossum5fe2c132001-07-05 15:27:19 +0000405\obindex{buffer}
406
407Xrange objects are similar to buffers in that there is no specific
Fred Drake4b270512002-05-02 05:56:04 +0000408syntax to create them, but they are created using the
409\function{xrange()} function.\bifuncindex{xrange} They don't support
Fred Drakeb9032012002-05-02 21:37:23 +0000410slicing, concatenation, or repetition, and using \keyword{in},
411\keyword{not} \keyword{in}, \function{min()} or \function{max()} on
412them is inefficient.
Fred Drake0b4e25d2000-10-04 04:21:19 +0000413\obindex{xrange}
Fred Drake64e3b431998-07-24 13:56:11 +0000414
Guido van Rossum5fe2c132001-07-05 15:27:19 +0000415Most sequence types support the following operations. The \samp{in} and
Fred Drake64e3b431998-07-24 13:56:11 +0000416\samp{not in} operations have the same priorities as the comparison
417operations. The \samp{+} and \samp{*} operations have the same
418priority as the corresponding numeric operations.\footnote{They must
419have since the parser can't tell the type of the operands.}
420
421This table lists the sequence operations sorted in ascending priority
422(operations in the same box have the same priority). In the table,
423\var{s} and \var{t} are sequences of the same type; \var{n}, \var{i}
424and \var{j} are integers:
425
426\begin{tableiii}{c|l|c}{code}{Operation}{Result}{Notes}
427 \lineiii{\var{x} in \var{s}}{\code{1} if an item of \var{s} is equal to \var{x}, else \code{0}}{}
428 \lineiii{\var{x} not in \var{s}}{\code{0} if an item of \var{s} is
429equal to \var{x}, else \code{1}}{}
430 \hline
431 \lineiii{\var{s} + \var{t}}{the concatenation of \var{s} and \var{t}}{}
Fred Draked800cff2001-08-28 14:56:05 +0000432 \lineiii{\var{s} * \var{n}\textrm{,} \var{n} * \var{s}}{\var{n} shallow copies of \var{s} concatenated}{(1)}
Fred Drake64e3b431998-07-24 13:56:11 +0000433 \hline
Fred Drake38e5d272000-04-03 20:13:55 +0000434 \lineiii{\var{s}[\var{i}]}{\var{i}'th item of \var{s}, origin 0}{(2)}
435 \lineiii{\var{s}[\var{i}:\var{j}]}{slice of \var{s} from \var{i} to \var{j}}{(2), (3)}
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +0000436 \lineiii{\var{s}[\var{i}:\var{j}:\var{k}]}{slice of \var{s} from \var{i} to \var{j} with step \var{k}}{(2), (4)}
Fred Drake64e3b431998-07-24 13:56:11 +0000437 \hline
438 \lineiii{len(\var{s})}{length of \var{s}}{}
439 \lineiii{min(\var{s})}{smallest item of \var{s}}{}
440 \lineiii{max(\var{s})}{largest item of \var{s}}{}
441\end{tableiii}
442\indexiii{operations on}{sequence}{types}
443\bifuncindex{len}
444\bifuncindex{min}
445\bifuncindex{max}
446\indexii{concatenation}{operation}
447\indexii{repetition}{operation}
448\indexii{subscript}{operation}
449\indexii{slice}{operation}
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +0000450\indexii{extended slice}{operation}
Fred Drake64e3b431998-07-24 13:56:11 +0000451\opindex{in}
452\opindex{not in}
453
454\noindent
455Notes:
456
457\begin{description}
Fred Drake38e5d272000-04-03 20:13:55 +0000458\item[(1)] Values of \var{n} less than \code{0} are treated as
459 \code{0} (which yields an empty sequence of the same type as
Fred Draked800cff2001-08-28 14:56:05 +0000460 \var{s}). Note also that the copies are shallow; nested structures
461 are not copied. This often haunts new Python programmers; consider:
462
463\begin{verbatim}
464>>> lists = [[]] * 3
465>>> lists
466[[], [], []]
467>>> lists[0].append(3)
468>>> lists
469[[3], [3], [3]]
470\end{verbatim}
471
472 What has happened is that \code{lists} is a list containing three
473 copies of the list \code{[[]]} (a one-element list containing an
474 empty list), but the contained list is shared by each copy. You can
475 create a list of different lists this way:
476
477\begin{verbatim}
478>>> lists = [[] for i in range(3)]
479>>> lists[0].append(3)
480>>> lists[1].append(5)
481>>> lists[2].append(7)
482>>> lists
483[[3], [5], [7]]
484\end{verbatim}
Fred Drake38e5d272000-04-03 20:13:55 +0000485
486\item[(2)] If \var{i} or \var{j} is negative, the index is relative to
Fred Drake907e76b2001-07-06 20:30:11 +0000487 the end of the string: \code{len(\var{s}) + \var{i}} or
Fred Drake64e3b431998-07-24 13:56:11 +0000488 \code{len(\var{s}) + \var{j}} is substituted. But note that \code{-0} is
489 still \code{0}.
Tim Peters8f01b682002-03-12 03:04:44 +0000490
Fred Drake38e5d272000-04-03 20:13:55 +0000491\item[(3)] The slice of \var{s} from \var{i} to \var{j} is defined as
Fred Drake64e3b431998-07-24 13:56:11 +0000492 the sequence of items with index \var{k} such that \code{\var{i} <=
493 \var{k} < \var{j}}. If \var{i} or \var{j} is greater than
494 \code{len(\var{s})}, use \code{len(\var{s})}. If \var{i} is omitted,
495 use \code{0}. If \var{j} is omitted, use \code{len(\var{s})}. If
496 \var{i} is greater than or equal to \var{j}, the slice is empty.
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +0000497
498\item[(4)] The slice of \var{s} from \var{i} to \var{j} with step \var{k}
499 is defined as the sequence of items with index \code{\var{x} =
500 \var{i} + \var{n}*\var{k}} such that \var{n} \code{>=} \code{0} and
501 \code{\var{i} <= \var{x} < \var{j}}. If \var{i} or \var{j} is
502 greater than \code{len(\var{s})}, use \code{len(\var{s})}. If
503 \var{i} or \var{j} are ommitted then they become ``end'' values
504 (which end depends on the sign of \var{k}).
505
Fred Drake64e3b431998-07-24 13:56:11 +0000506\end{description}
507
Fred Drake9474d861999-02-12 22:05:33 +0000508
Fred Drake4de96c22000-08-12 03:36:23 +0000509\subsubsection{String Methods \label{string-methods}}
510
511These are the string methods which both 8-bit strings and Unicode
512objects support:
513
514\begin{methoddesc}[string]{capitalize}{}
515Return a copy of the string with only its first character capitalized.
516\end{methoddesc}
517
518\begin{methoddesc}[string]{center}{width}
519Return centered in a string of length \var{width}. Padding is done
520using spaces.
521\end{methoddesc}
522
523\begin{methoddesc}[string]{count}{sub\optional{, start\optional{, end}}}
524Return the number of occurrences of substring \var{sub} in string
525S\code{[\var{start}:\var{end}]}. Optional arguments \var{start} and
526\var{end} are interpreted as in slice notation.
527\end{methoddesc}
528
Fred Drake6048ce92001-12-10 16:43:08 +0000529\begin{methoddesc}[string]{decode}{\optional{encoding\optional{, errors}}}
530Decodes the string using the codec registered for \var{encoding}.
531\var{encoding} defaults to the default string encoding. \var{errors}
532may be given to set a different error handling scheme. The default is
533\code{'strict'}, meaning that encoding errors raise
534\exception{ValueError}. Other possible values are \code{'ignore'} and
535\code{replace'}.
536\versionadded{2.2}
537\end{methoddesc}
538
Fred Drake4de96c22000-08-12 03:36:23 +0000539\begin{methoddesc}[string]{encode}{\optional{encoding\optional{,errors}}}
540Return an encoded version of the string. Default encoding is the current
541default string encoding. \var{errors} may be given to set a different
542error handling scheme. The default for \var{errors} is
543\code{'strict'}, meaning that encoding errors raise a
544\exception{ValueError}. Other possible values are \code{'ignore'} and
545\code{'replace'}.
Fred Drake1dba66c2000-10-25 21:03:55 +0000546\versionadded{2.0}
Fred Drake4de96c22000-08-12 03:36:23 +0000547\end{methoddesc}
548
549\begin{methoddesc}[string]{endswith}{suffix\optional{, start\optional{, end}}}
550Return true if the string ends with the specified \var{suffix},
551otherwise return false. With optional \var{start}, test beginning at
552that position. With optional \var{end}, stop comparing at that position.
553\end{methoddesc}
554
555\begin{methoddesc}[string]{expandtabs}{\optional{tabsize}}
556Return a copy of the string where all tab characters are expanded
557using spaces. If \var{tabsize} is not given, a tab size of \code{8}
558characters is assumed.
559\end{methoddesc}
560
561\begin{methoddesc}[string]{find}{sub\optional{, start\optional{, end}}}
562Return the lowest index in the string where substring \var{sub} is
563found, such that \var{sub} is contained in the range [\var{start},
564\var{end}). Optional arguments \var{start} and \var{end} are
565interpreted as in slice notation. Return \code{-1} if \var{sub} is
566not found.
567\end{methoddesc}
568
569\begin{methoddesc}[string]{index}{sub\optional{, start\optional{, end}}}
570Like \method{find()}, but raise \exception{ValueError} when the
571substring is not found.
572\end{methoddesc}
573
574\begin{methoddesc}[string]{isalnum}{}
575Return true if all characters in the string are alphanumeric and there
576is at least one character, false otherwise.
577\end{methoddesc}
578
579\begin{methoddesc}[string]{isalpha}{}
580Return true if all characters in the string are alphabetic and there
581is at least one character, false otherwise.
582\end{methoddesc}
583
584\begin{methoddesc}[string]{isdigit}{}
585Return true if there are only digit characters, false otherwise.
586\end{methoddesc}
587
588\begin{methoddesc}[string]{islower}{}
589Return true if all cased characters in the string are lowercase and
590there is at least one cased character, false otherwise.
591\end{methoddesc}
592
593\begin{methoddesc}[string]{isspace}{}
594Return true if there are only whitespace characters in the string and
595the string is not empty, false otherwise.
596\end{methoddesc}
597
598\begin{methoddesc}[string]{istitle}{}
Fred Drake907e76b2001-07-06 20:30:11 +0000599Return true if the string is a titlecased string: uppercase
Fred Drake4de96c22000-08-12 03:36:23 +0000600characters may only follow uncased characters and lowercase characters
601only cased ones. Return false otherwise.
602\end{methoddesc}
603
604\begin{methoddesc}[string]{isupper}{}
605Return true if all cased characters in the string are uppercase and
606there is at least one cased character, false otherwise.
607\end{methoddesc}
608
609\begin{methoddesc}[string]{join}{seq}
610Return a string which is the concatenation of the strings in the
611sequence \var{seq}. The separator between elements is the string
612providing this method.
613\end{methoddesc}
614
615\begin{methoddesc}[string]{ljust}{width}
616Return the string left justified in a string of length \var{width}.
617Padding is done using spaces. The original string is returned if
618\var{width} is less than \code{len(\var{s})}.
619\end{methoddesc}
620
621\begin{methoddesc}[string]{lower}{}
622Return a copy of the string converted to lowercase.
623\end{methoddesc}
624
Fred Drake8b1c47b2002-04-13 02:43:39 +0000625\begin{methoddesc}[string]{lstrip}{\optional{chars}}
626Return a copy of the string with leading characters removed. If
627\var{chars} is omitted or \code{None}, whitespace characters are
628removed. If given and not \code{None}, \var{chars} must be a string;
629the characters in the string will be stripped from the beginning of
630the string this method is called on.
Fred Drake4de96c22000-08-12 03:36:23 +0000631\end{methoddesc}
632
633\begin{methoddesc}[string]{replace}{old, new\optional{, maxsplit}}
634Return a copy of the string with all occurrences of substring
635\var{old} replaced by \var{new}. If the optional argument
636\var{maxsplit} is given, only the first \var{maxsplit} occurrences are
637replaced.
638\end{methoddesc}
639
640\begin{methoddesc}[string]{rfind}{sub \optional{,start \optional{,end}}}
641Return the highest index in the string where substring \var{sub} is
642found, such that \var{sub} is contained within s[start,end]. Optional
643arguments \var{start} and \var{end} are interpreted as in slice
644notation. Return \code{-1} on failure.
645\end{methoddesc}
646
647\begin{methoddesc}[string]{rindex}{sub\optional{, start\optional{, end}}}
648Like \method{rfind()} but raises \exception{ValueError} when the
649substring \var{sub} is not found.
650\end{methoddesc}
651
652\begin{methoddesc}[string]{rjust}{width}
653Return the string right justified in a string of length \var{width}.
654Padding is done using spaces. The original string is returned if
655\var{width} is less than \code{len(\var{s})}.
656\end{methoddesc}
657
Fred Drake8b1c47b2002-04-13 02:43:39 +0000658\begin{methoddesc}[string]{rstrip}{\optional{chars}}
659Return a copy of the string with trailing characters removed. If
660\var{chars} is omitted or \code{None}, whitespace characters are
661removed. If given and not \code{None}, \var{chars} must be a string;
662the characters in the string will be stripped from the end of the
663string this method is called on.
Fred Drake4de96c22000-08-12 03:36:23 +0000664\end{methoddesc}
665
666\begin{methoddesc}[string]{split}{\optional{sep \optional{,maxsplit}}}
667Return a list of the words in the string, using \var{sep} as the
668delimiter string. If \var{maxsplit} is given, at most \var{maxsplit}
669splits are done. If \var{sep} is not specified or \code{None}, any
670whitespace string is a separator.
671\end{methoddesc}
672
673\begin{methoddesc}[string]{splitlines}{\optional{keepends}}
674Return a list of the lines in the string, breaking at line
675boundaries. Line breaks are not included in the resulting list unless
676\var{keepends} is given and true.
677\end{methoddesc}
678
Fred Drake8b1c47b2002-04-13 02:43:39 +0000679\begin{methoddesc}[string]{startswith}{prefix\optional{,
680 start\optional{, end}}}
Fred Drake4de96c22000-08-12 03:36:23 +0000681Return true if string starts with the \var{prefix}, otherwise
682return false. With optional \var{start}, test string beginning at
683that position. With optional \var{end}, stop comparing string at that
684position.
685\end{methoddesc}
686
Fred Drake8b1c47b2002-04-13 02:43:39 +0000687\begin{methoddesc}[string]{strip}{\optional{chars}}
688Return a copy of the string with leading and trailing characters
689removed. If \var{chars} is omitted or \code{None}, whitespace
690characters are removed. If given and not \code{None}, \var{chars}
691must be a string; the characters in the string will be stripped from
692the both ends of the string this method is called on.
Fred Drake4de96c22000-08-12 03:36:23 +0000693\end{methoddesc}
694
695\begin{methoddesc}[string]{swapcase}{}
696Return a copy of the string with uppercase characters converted to
697lowercase and vice versa.
698\end{methoddesc}
699
700\begin{methoddesc}[string]{title}{}
Fred Drake907e76b2001-07-06 20:30:11 +0000701Return a titlecased version of the string: words start with uppercase
Fred Drake4de96c22000-08-12 03:36:23 +0000702characters, all remaining cased characters are lowercase.
703\end{methoddesc}
704
705\begin{methoddesc}[string]{translate}{table\optional{, deletechars}}
706Return a copy of the string where all characters occurring in the
707optional argument \var{deletechars} are removed, and the remaining
708characters have been mapped through the given translation table, which
709must be a string of length 256.
710\end{methoddesc}
711
712\begin{methoddesc}[string]{upper}{}
713Return a copy of the string converted to uppercase.
714\end{methoddesc}
715
Walter Dörwald068325e2002-04-15 13:36:47 +0000716\begin{methoddesc}[string]{zfill}{width}
717Return the numeric string left filled with zeros in a string
718of length \var{width}. The original string is returned if
719\var{width} is less than \code{len(\var{s})}.
720\end{methoddesc}
721
Fred Drake4de96c22000-08-12 03:36:23 +0000722
723\subsubsection{String Formatting Operations \label{typesseq-strings}}
Fred Drake64e3b431998-07-24 13:56:11 +0000724
Fred Drakeb38784e2001-12-03 22:15:56 +0000725\index{formatting, string (\%{})}
Fred Drakeab2dc1d2001-12-26 20:06:40 +0000726\index{interpolation, string (\%{})}
Fred Drake66d32b12000-09-14 17:57:42 +0000727\index{string!formatting}
Fred Drakeab2dc1d2001-12-26 20:06:40 +0000728\index{string!interpolation}
Fred Drake66d32b12000-09-14 17:57:42 +0000729\index{printf-style formatting}
730\index{sprintf-style formatting}
Fred Drakeb38784e2001-12-03 22:15:56 +0000731\index{\protect\%{} formatting}
Fred Drakeab2dc1d2001-12-26 20:06:40 +0000732\index{\protect\%{} interpolation}
Fred Drake66d32b12000-09-14 17:57:42 +0000733
Fred Drake8c071d42001-01-26 20:48:35 +0000734String and Unicode objects have one unique built-in operation: the
Fred Drakeab2dc1d2001-12-26 20:06:40 +0000735\code{\%} operator (modulo). This is also known as the string
736\emph{formatting} or \emph{interpolation} operator. Given
737\code{\var{format} \% \var{values}} (where \var{format} is a string or
738Unicode object), \code{\%} conversion specifications in \var{format}
739are replaced with zero or more elements of \var{values}. The effect
740is similar to the using \cfunction{sprintf()} in the C language. If
741\var{format} is a Unicode object, or if any of the objects being
742converted using the \code{\%s} conversion are Unicode objects, the
743result will be a Unicode object as well.
Fred Drake64e3b431998-07-24 13:56:11 +0000744
Fred Drake8c071d42001-01-26 20:48:35 +0000745If \var{format} requires a single argument, \var{values} may be a
746single non-tuple object. \footnote{A tuple object in this case should
747 be a singleton.} Otherwise, \var{values} must be a tuple with
748exactly the number of items specified by the format string, or a
749single mapping object (for example, a dictionary).
Fred Drake64e3b431998-07-24 13:56:11 +0000750
Fred Drake8c071d42001-01-26 20:48:35 +0000751A conversion specifier contains two or more characters and has the
752following components, which must occur in this order:
753
754\begin{enumerate}
755 \item The \character{\%} character, which marks the start of the
756 specifier.
757 \item Mapping key value (optional), consisting of an identifier in
758 parentheses (for example, \code{(somename)}).
759 \item Conversion flags (optional), which affect the result of some
760 conversion types.
761 \item Minimum field width (optional). If specified as an
762 \character{*} (asterisk), the actual width is read from the
763 next element of the tuple in \var{values}, and the object to
764 convert comes after the minimum field width and optional
765 precision.
766 \item Precision (optional), given as a \character{.} (dot) followed
767 by the precision. If specified as \character{*} (an
768 asterisk), the actual width is read from the next element of
769 the tuple in \var{values}, and the value to convert comes after
770 the precision.
771 \item Length modifier (optional).
772 \item Conversion type.
773\end{enumerate}
Fred Drake64e3b431998-07-24 13:56:11 +0000774
775If the right argument is a dictionary (or any kind of mapping), then
Fred Drake8c071d42001-01-26 20:48:35 +0000776the formats in the string \emph{must} have a parenthesized key into
777that dictionary inserted immediately after the \character{\%}
778character, and each format formats the corresponding entry from the
779mapping. For example:
Fred Drake64e3b431998-07-24 13:56:11 +0000780
781\begin{verbatim}
782>>> count = 2
783>>> language = 'Python'
784>>> print '%(language)s has %(count)03d quote types.' % vars()
785Python has 002 quote types.
786\end{verbatim}
787
788In this case no \code{*} specifiers may occur in a format (since they
789require a sequential parameter list).
790
Fred Drake8c071d42001-01-26 20:48:35 +0000791The conversion flag characters are:
792
793\begin{tableii}{c|l}{character}{Flag}{Meaning}
794 \lineii{\#}{The value conversion will use the ``alternate form''
795 (where defined below).}
796 \lineii{0}{The conversion will be zero padded.}
797 \lineii{-}{The converted value is left adjusted (overrides
798 \character{-}).}
799 \lineii{{~}}{(a space) A blank should be left before a positive number
800 (or empty string) produced by a signed conversion.}
801 \lineii{+}{A sign character (\character{+} or \character{-}) will
802 precede the conversion (overrides a "space" flag).}
803\end{tableii}
804
805The length modifier may be \code{h}, \code{l}, and \code{L} may be
806present, but are ignored as they are not necessary for Python.
807
808The conversion types are:
809
810\begin{tableii}{c|l}{character}{Conversion}{Meaning}
811 \lineii{d}{Signed integer decimal.}
812 \lineii{i}{Signed integer decimal.}
813 \lineii{o}{Unsigned octal.}
814 \lineii{u}{Unsigned decimal.}
815 \lineii{x}{Unsigned hexidecimal (lowercase).}
816 \lineii{X}{Unsigned hexidecimal (uppercase).}
817 \lineii{e}{Floating point exponential format (lowercase).}
818 \lineii{E}{Floating point exponential format (uppercase).}
819 \lineii{f}{Floating point decimal format.}
820 \lineii{F}{Floating point decimal format.}
821 \lineii{g}{Same as \character{e} if exponent is greater than -4 or
822 less than precision, \character{f} otherwise.}
823 \lineii{G}{Same as \character{E} if exponent is greater than -4 or
824 less than precision, \character{F} otherwise.}
825 \lineii{c}{Single character (accepts integer or single character
826 string).}
827 \lineii{r}{String (converts any python object using
828 \function{repr()}).}
829 \lineii{s}{String (converts any python object using
830 \function{str()}).}
831 \lineii{\%}{No argument is converted, results in a \character{\%}
832 character in the result. (The complete specification is
833 \code{\%\%}.)}
834\end{tableii}
835
836% XXX Examples?
837
Fred Drake52cc6702002-04-30 14:54:47 +0000838(The \code{\%r} conversion was added in Python 2.0.)
Fred Drake8c071d42001-01-26 20:48:35 +0000839
840Since Python strings have an explicit length, \code{\%s} conversions
841do not assume that \code{'\e0'} is the end of the string.
842
843For safety reasons, floating point precisions are clipped to 50;
844\code{\%f} conversions for numbers whose absolute value is over 1e25
845are replaced by \code{\%g} conversions.\footnote{
846 These numbers are fairly arbitrary. They are intended to
847 avoid printing endless strings of meaningless digits without hampering
848 correct use and without having to know the exact precision of floating
849 point values on a particular machine.
850} All other errors raise exceptions.
851
Fred Drake14f5c5f2001-12-03 18:33:13 +0000852Additional string operations are defined in standard modules
853\refmodule{string}\refstmodindex{string} and
Tim Peters8f01b682002-03-12 03:04:44 +0000854\refmodule{re}.\refstmodindex{re}
Fred Drake64e3b431998-07-24 13:56:11 +0000855
Fred Drake107b9672000-08-14 15:37:59 +0000856
Fred Drake512bb722000-08-18 03:12:38 +0000857\subsubsection{XRange Type \label{typesseq-xrange}}
Fred Drake107b9672000-08-14 15:37:59 +0000858
Fred Drake0b4e25d2000-10-04 04:21:19 +0000859The xrange\obindex{xrange} type is an immutable sequence which is
Fred Drake512bb722000-08-18 03:12:38 +0000860commonly used for looping. The advantage of the xrange type is that an
861xrange object will always take the same amount of memory, no matter the
Fred Drake107b9672000-08-14 15:37:59 +0000862size of the range it represents. There are no consistent performance
863advantages.
864
Guido van Rossum3f561662001-07-05 13:27:48 +0000865XRange objects have very little behavior: they only support indexing
866and the \function{len()} function.
Fred Drake107b9672000-08-14 15:37:59 +0000867
868
Fred Drake9474d861999-02-12 22:05:33 +0000869\subsubsection{Mutable Sequence Types \label{typesseq-mutable}}
Fred Drake64e3b431998-07-24 13:56:11 +0000870
871List objects support additional operations that allow in-place
872modification of the object.
873These operations would be supported by other mutable sequence types
874(when added to the language) as well.
875Strings and tuples are immutable sequence types and such objects cannot
876be modified once created.
877The following operations are defined on mutable sequence types (where
878\var{x} is an arbitrary object):
879\indexiii{mutable}{sequence}{types}
Fred Drake0b4e25d2000-10-04 04:21:19 +0000880\obindex{list}
Fred Drake64e3b431998-07-24 13:56:11 +0000881
882\begin{tableiii}{c|l|c}{code}{Operation}{Result}{Notes}
883 \lineiii{\var{s}[\var{i}] = \var{x}}
884 {item \var{i} of \var{s} is replaced by \var{x}}{}
885 \lineiii{\var{s}[\var{i}:\var{j}] = \var{t}}
886 {slice of \var{s} from \var{i} to \var{j} is replaced by \var{t}}{}
887 \lineiii{del \var{s}[\var{i}:\var{j}]}
888 {same as \code{\var{s}[\var{i}:\var{j}] = []}}{}
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +0000889 \lineiii{\var{s}[\var{i}:\var{j}:\var{k}] = \var{t}}
890 {the elements of \code{\var{s}[\var{i}:\var{j}:\var{k}]} are replaced by those of \var{t}}{(1)}
891 \lineiii{del \var{s}[\var{i}:\var{j}:\var{k}]}
892 {removes the elements of \code{\var{s}[\var{i}:\var{j}:\var{k}]} from the list}{}
Fred Drake64e3b431998-07-24 13:56:11 +0000893 \lineiii{\var{s}.append(\var{x})}
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +0000894 {same as \code{\var{s}[len(\var{s}):len(\var{s})] = [\var{x}]}}{(2)}
Barry Warsawafd974c1998-10-09 16:39:58 +0000895 \lineiii{\var{s}.extend(\var{x})}
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +0000896 {same as \code{\var{s}[len(\var{s}):len(\var{s})] = \var{x}}}{(3)}
Fred Drake64e3b431998-07-24 13:56:11 +0000897 \lineiii{\var{s}.count(\var{x})}
898 {return number of \var{i}'s for which \code{\var{s}[\var{i}] == \var{x}}}{}
899 \lineiii{\var{s}.index(\var{x})}
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +0000900 {return smallest \var{i} such that \code{\var{s}[\var{i}] == \var{x}}}{(4)}
Fred Drake64e3b431998-07-24 13:56:11 +0000901 \lineiii{\var{s}.insert(\var{i}, \var{x})}
902 {same as \code{\var{s}[\var{i}:\var{i}] = [\var{x}]}
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +0000903 if \code{\var{i} >= 0}}{(5)}
Fred Drake64e3b431998-07-24 13:56:11 +0000904 \lineiii{\var{s}.pop(\optional{\var{i}})}
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +0000905 {same as \code{\var{x} = \var{s}[\var{i}]; del \var{s}[\var{i}]; return \var{x}}}{(6)}
Fred Drake64e3b431998-07-24 13:56:11 +0000906 \lineiii{\var{s}.remove(\var{x})}
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +0000907 {same as \code{del \var{s}[\var{s}.index(\var{x})]}}{(4)}
Fred Drake64e3b431998-07-24 13:56:11 +0000908 \lineiii{\var{s}.reverse()}
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +0000909 {reverses the items of \var{s} in place}{(7)}
Fred Drake64e3b431998-07-24 13:56:11 +0000910 \lineiii{\var{s}.sort(\optional{\var{cmpfunc}})}
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +0000911 {sort the items of \var{s} in place}{(7), (8)}
Fred Drake64e3b431998-07-24 13:56:11 +0000912\end{tableiii}
913\indexiv{operations on}{mutable}{sequence}{types}
914\indexiii{operations on}{sequence}{types}
915\indexiii{operations on}{list}{type}
916\indexii{subscript}{assignment}
917\indexii{slice}{assignment}
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +0000918\indexii{extended slice}{assignment}
Fred Drake64e3b431998-07-24 13:56:11 +0000919\stindex{del}
Fred Drake9474d861999-02-12 22:05:33 +0000920\withsubitem{(list method)}{
Fred Drake68921df1999-08-09 17:05:12 +0000921 \ttindex{append()}\ttindex{extend()}\ttindex{count()}\ttindex{index()}
922 \ttindex{insert()}\ttindex{pop()}\ttindex{remove()}\ttindex{reverse()}
Fred Drakee8391991998-11-25 17:09:19 +0000923 \ttindex{sort()}}
Fred Drake64e3b431998-07-24 13:56:11 +0000924\noindent
925Notes:
926\begin{description}
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +0000927\item[(1)] \var{t} must have the same length as the slice it is
928 replacing.
929
930\item[(2)] The C implementation of Python has historically accepted
Fred Drake38e5d272000-04-03 20:13:55 +0000931 multiple parameters and implicitly joined them into a tuple; this
Fred Drake30f76ff2000-06-30 16:06:19 +0000932 no longer works in Python 2.0. Use of this misfeature has been
Fred Drake38e5d272000-04-03 20:13:55 +0000933 deprecated since Python 1.4.
934
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +0000935\item[(3)] Raises an exception when \var{x} is not a list object. The
Fred Drake38e5d272000-04-03 20:13:55 +0000936 \method{extend()} method is experimental and not supported by
937 mutable sequence types other than lists.
938
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +0000939\item[(4)] Raises \exception{ValueError} when \var{x} is not found in
Fred Drake68921df1999-08-09 17:05:12 +0000940 \var{s}.
941
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +0000942\item[(5)] When a negative index is passed as the first parameter to
Fred Drakeef428a22001-10-26 18:57:14 +0000943 the \method{insert()} method, the new element is prepended to the
944 sequence.
945
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +0000946\item[(6)] The \method{pop()} method is only supported by the list and
Fred Drakefbd3b452000-07-31 23:42:23 +0000947 array types. The optional argument \var{i} defaults to \code{-1},
948 so that by default the last item is removed and returned.
Fred Drake38e5d272000-04-03 20:13:55 +0000949
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +0000950\item[(7)] The \method{sort()} and \method{reverse()} methods modify the
Fred Drake38e5d272000-04-03 20:13:55 +0000951 list in place for economy of space when sorting or reversing a large
Skip Montanaro41d7d582001-07-25 16:18:19 +0000952 list. To remind you that they operate by side effect, they don't return
953 the sorted or reversed list.
Fred Drake38e5d272000-04-03 20:13:55 +0000954
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +0000955\item[(8)] The \method{sort()} method takes an optional argument
Fred Drake64e3b431998-07-24 13:56:11 +0000956 specifying a comparison function of two arguments (list items) which
Tim Peters599db7d2001-09-29 01:08:19 +0000957 should return a negative, zero or positive number depending on whether
Fred Drake68921df1999-08-09 17:05:12 +0000958 the first argument is considered smaller than, equal to, or larger
959 than the second argument. Note that this slows the sorting process
960 down considerably; e.g. to sort a list in reverse order it is much
961 faster to use calls to the methods \method{sort()} and
962 \method{reverse()} than to use the built-in function
963 \function{sort()} with a comparison function that reverses the
964 ordering of the elements.
Fred Drake64e3b431998-07-24 13:56:11 +0000965\end{description}
966
967
Fred Drake7a2f0661998-09-10 18:25:58 +0000968\subsection{Mapping Types \label{typesmapping}}
Fred Drake0b4e25d2000-10-04 04:21:19 +0000969\obindex{mapping}
970\obindex{dictionary}
Fred Drake64e3b431998-07-24 13:56:11 +0000971
972A \dfn{mapping} object maps values of one type (the key type) to
973arbitrary objects. Mappings are mutable objects. There is currently
974only one standard mapping type, the \dfn{dictionary}. A dictionary's keys are
975almost arbitrary values. The only types of values not acceptable as
976keys are values containing lists or dictionaries or other mutable
977types that are compared by value rather than by object identity.
978Numeric types used for keys obey the normal rules for numeric
979comparison: if two numbers compare equal (e.g. \code{1} and
980\code{1.0}) then they can be used interchangeably to index the same
981dictionary entry.
982
Fred Drake64e3b431998-07-24 13:56:11 +0000983Dictionaries are created by placing a comma-separated list of
984\code{\var{key}: \var{value}} pairs within braces, for example:
985\code{\{'jack': 4098, 'sjoerd': 4127\}} or
986\code{\{4098: 'jack', 4127: 'sjoerd'\}}.
987
Fred Drake9c5cc141999-06-10 22:37:34 +0000988The following operations are defined on mappings (where \var{a} and
989\var{b} are mappings, \var{k} is a key, and \var{v} and \var{x} are
990arbitrary objects):
Fred Drake64e3b431998-07-24 13:56:11 +0000991\indexiii{operations on}{mapping}{types}
992\indexiii{operations on}{dictionary}{type}
993\stindex{del}
994\bifuncindex{len}
Fred Drake9474d861999-02-12 22:05:33 +0000995\withsubitem{(dictionary method)}{
996 \ttindex{clear()}
997 \ttindex{copy()}
998 \ttindex{has_key()}
999 \ttindex{items()}
1000 \ttindex{keys()}
1001 \ttindex{update()}
1002 \ttindex{values()}
Raymond Hettingerb07fa392002-05-15 15:45:25 +00001003 \ttindex{get()}
1004 \ttindex{setdefault()}
1005 \ttindex{pop()}
1006 \ttindex{popitem()}
1007 \ttindex{iteritems()}
1008 \ttindex{iterkeys)}
1009 \ttindex{itervalues()}}
Fred Drake9c5cc141999-06-10 22:37:34 +00001010
1011\begin{tableiii}{c|l|c}{code}{Operation}{Result}{Notes}
1012 \lineiii{len(\var{a})}{the number of items in \var{a}}{}
1013 \lineiii{\var{a}[\var{k}]}{the item of \var{a} with key \var{k}}{(1)}
Fred Drake1e75e172000-07-31 16:34:46 +00001014 \lineiii{\var{a}[\var{k}] = \var{v}}
1015 {set \code{\var{a}[\var{k}]} to \var{v}}
Fred Drake9c5cc141999-06-10 22:37:34 +00001016 {}
1017 \lineiii{del \var{a}[\var{k}]}
1018 {remove \code{\var{a}[\var{k}]} from \var{a}}
1019 {(1)}
1020 \lineiii{\var{a}.clear()}{remove all items from \code{a}}{}
1021 \lineiii{\var{a}.copy()}{a (shallow) copy of \code{a}}{}
Guido van Rossum8b3d6ca2001-04-23 13:22:59 +00001022 \lineiii{\var{a}.has_key(\var{k})}
Fred Drake9c5cc141999-06-10 22:37:34 +00001023 {\code{1} if \var{a} has a key \var{k}, else \code{0}}
1024 {}
Guido van Rossum8b3d6ca2001-04-23 13:22:59 +00001025 \lineiii{\var{k} \code{in} \var{a}}
1026 {Equivalent to \var{a}.has_key(\var{k})}
Fred Drakec6d8f8d2001-05-25 04:24:37 +00001027 {(2)}
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00001028 \lineiii{\var{k} not in \var{a}}
Guido van Rossum8b3d6ca2001-04-23 13:22:59 +00001029 {Equivalent to \code{not} \var{a}.has_key(\var{k})}
Fred Drakec6d8f8d2001-05-25 04:24:37 +00001030 {(2)}
Fred Drake9c5cc141999-06-10 22:37:34 +00001031 \lineiii{\var{a}.items()}
1032 {a copy of \var{a}'s list of (\var{key}, \var{value}) pairs}
Fred Drakec6d8f8d2001-05-25 04:24:37 +00001033 {(3)}
Fred Drake4a6c5c52001-06-12 03:31:56 +00001034 \lineiii{\var{a}.keys()}{a copy of \var{a}'s list of keys}{(3)}
Fred Drake9c5cc141999-06-10 22:37:34 +00001035 \lineiii{\var{a}.update(\var{b})}
Fred Drake1e75e172000-07-31 16:34:46 +00001036 {\code{for k in \var{b}.keys(): \var{a}[k] = \var{b}[k]}}
Barry Warsawe9218a12001-06-26 20:32:59 +00001037 {}
Fred Drake4a6c5c52001-06-12 03:31:56 +00001038 \lineiii{\var{a}.values()}{a copy of \var{a}'s list of values}{(3)}
Fred Drake9c5cc141999-06-10 22:37:34 +00001039 \lineiii{\var{a}.get(\var{k}\optional{, \var{x}})}
Fred Drake4cacec52001-04-21 05:56:06 +00001040 {\code{\var{a}[\var{k}]} if \code{\var{k} in \var{a}},
Fred Drake9c5cc141999-06-10 22:37:34 +00001041 else \var{x}}
Barry Warsawe9218a12001-06-26 20:32:59 +00001042 {(4)}
Guido van Rossum8141cf52000-08-08 16:15:49 +00001043 \lineiii{\var{a}.setdefault(\var{k}\optional{, \var{x}})}
Fred Drake4cacec52001-04-21 05:56:06 +00001044 {\code{\var{a}[\var{k}]} if \code{\var{k} in \var{a}},
Guido van Rossum8141cf52000-08-08 16:15:49 +00001045 else \var{x} (also setting it)}
Barry Warsawe9218a12001-06-26 20:32:59 +00001046 {(5)}
Guido van Rossume027d982002-04-12 15:11:59 +00001047 \lineiii{\var{a}.pop(\var{k})}
1048 {remove specified \var{key} and return corresponding \var{value}}
1049 {}
Guido van Rossumff63f202000-12-12 22:03:47 +00001050 \lineiii{\var{a}.popitem()}
1051 {remove and return an arbitrary (\var{key}, \var{value}) pair}
Barry Warsawe9218a12001-06-26 20:32:59 +00001052 {(6)}
Fred Drakec6d8f8d2001-05-25 04:24:37 +00001053 \lineiii{\var{a}.iteritems()}
1054 {return an iterator over (\var{key}, \var{value}) pairs}
1055 {(2)}
1056 \lineiii{\var{a}.iterkeys()}
1057 {return an iterator over the mapping's keys}
1058 {(2)}
1059 \lineiii{\var{a}.itervalues()}
1060 {return an iterator over the mapping's values}
1061 {(2)}
Fred Drake9c5cc141999-06-10 22:37:34 +00001062\end{tableiii}
1063
Fred Drake64e3b431998-07-24 13:56:11 +00001064\noindent
1065Notes:
1066\begin{description}
Fred Drake9c5cc141999-06-10 22:37:34 +00001067\item[(1)] Raises a \exception{KeyError} exception if \var{k} is not
1068in the map.
Fred Drake64e3b431998-07-24 13:56:11 +00001069
Fred Drakec6d8f8d2001-05-25 04:24:37 +00001070\item[(2)] \versionadded{2.2}
1071
1072\item[(3)] Keys and values are listed in random order. If
Fred Drake38e5d272000-04-03 20:13:55 +00001073\method{keys()} and \method{values()} are called with no intervening
1074modifications to the dictionary, the two lists will directly
1075correspond. This allows the creation of \code{(\var{value},
Fred Drake4a6c5c52001-06-12 03:31:56 +00001076\var{key})} pairs using \function{zip()}: \samp{pairs =
1077zip(\var{a}.values(), \var{a}.keys())}.
Fred Drake64e3b431998-07-24 13:56:11 +00001078
Barry Warsawe9218a12001-06-26 20:32:59 +00001079\item[(4)] Never raises an exception if \var{k} is not in the map,
Fred Drake38e5d272000-04-03 20:13:55 +00001080instead it returns \var{x}. \var{x} is optional; when \var{x} is not
Fred Drake9c5cc141999-06-10 22:37:34 +00001081provided and \var{k} is not in the map, \code{None} is returned.
Guido van Rossum8141cf52000-08-08 16:15:49 +00001082
Barry Warsawe9218a12001-06-26 20:32:59 +00001083\item[(5)] \function{setdefault()} is like \function{get()}, except
Guido van Rossum8141cf52000-08-08 16:15:49 +00001084that if \var{k} is missing, \var{x} is both returned and inserted into
1085the dictionary as the value of \var{k}.
Guido van Rossumff63f202000-12-12 22:03:47 +00001086
Barry Warsawe9218a12001-06-26 20:32:59 +00001087\item[(6)] \function{popitem()} is useful to destructively iterate
Guido van Rossumff63f202000-12-12 22:03:47 +00001088over a dictionary, as often used in set algorithms.
Fred Drake64e3b431998-07-24 13:56:11 +00001089\end{description}
1090
1091
Fred Drake99de2182001-10-30 06:23:14 +00001092\subsection{File Objects
1093 \label{bltin-file-objects}}
Fred Drake64e3b431998-07-24 13:56:11 +00001094
Fred Drake99de2182001-10-30 06:23:14 +00001095File objects\obindex{file} are implemented using C's \code{stdio}
1096package and can be created with the built-in constructor
Tim Peters8f01b682002-03-12 03:04:44 +00001097\function{file()}\bifuncindex{file} described in section
Tim Peters003047a2001-10-30 05:54:04 +00001098\ref{built-in-funcs}, ``Built-in Functions.''\footnote{\function{file()}
1099is new in Python 2.2. The older built-in \function{open()} is an
1100alias for \function{file()}.}
1101They are also returned
Fred Drake907e76b2001-07-06 20:30:11 +00001102by some other built-in functions and methods, such as
Fred Drake4de96c22000-08-12 03:36:23 +00001103\function{os.popen()} and \function{os.fdopen()} and the
Fred Drake130072d1998-10-28 20:08:35 +00001104\method{makefile()} method of socket objects.
Fred Drake4de96c22000-08-12 03:36:23 +00001105\refstmodindex{os}
Fred Drake64e3b431998-07-24 13:56:11 +00001106\refbimodindex{socket}
1107
1108When a file operation fails for an I/O-related reason, the exception
Fred Drake84538cd1998-11-30 21:51:25 +00001109\exception{IOError} is raised. This includes situations where the
1110operation is not defined for some reason, like \method{seek()} on a tty
Fred Drake64e3b431998-07-24 13:56:11 +00001111device or writing a file opened for reading.
1112
1113Files have the following methods:
1114
1115
1116\begin{methoddesc}[file]{close}{}
1117 Close the file. A closed file cannot be read or written anymore.
Fred Drakea776cea2000-11-06 20:17:37 +00001118 Any operation which requires that the file be open will raise a
1119 \exception{ValueError} after the file has been closed. Calling
Fred Drake752ba392000-09-19 15:18:51 +00001120 \method{close()} more than once is allowed.
Fred Drake64e3b431998-07-24 13:56:11 +00001121\end{methoddesc}
1122
1123\begin{methoddesc}[file]{flush}{}
Fred Drake752ba392000-09-19 15:18:51 +00001124 Flush the internal buffer, like \code{stdio}'s
1125 \cfunction{fflush()}. This may be a no-op on some file-like
1126 objects.
Fred Drake64e3b431998-07-24 13:56:11 +00001127\end{methoddesc}
1128
1129\begin{methoddesc}[file]{isatty}{}
Neal Norwitz6b353702002-04-09 18:15:00 +00001130 Return \code{True} if the file is connected to a tty(-like) device, else
1131 \code{False}. \note{If a file-like object is not associated
Fred Drake0aa811c2001-10-20 04:24:09 +00001132 with a real file, this method should \emph{not} be implemented.}
Fred Drake64e3b431998-07-24 13:56:11 +00001133\end{methoddesc}
1134
1135\begin{methoddesc}[file]{fileno}{}
Fred Drake752ba392000-09-19 15:18:51 +00001136 \index{file descriptor}
1137 \index{descriptor, file}
1138 Return the integer ``file descriptor'' that is used by the
1139 underlying implementation to request I/O operations from the
1140 operating system. This can be useful for other, lower level
Fred Drake907e76b2001-07-06 20:30:11 +00001141 interfaces that use file descriptors, such as the
1142 \refmodule{fcntl}\refbimodindex{fcntl} module or
Fred Drake0aa811c2001-10-20 04:24:09 +00001143 \function{os.read()} and friends. \note{File-like objects
Fred Drake907e76b2001-07-06 20:30:11 +00001144 which do not have a real file descriptor should \emph{not} provide
Fred Drake0aa811c2001-10-20 04:24:09 +00001145 this method!}
Fred Drake64e3b431998-07-24 13:56:11 +00001146\end{methoddesc}
1147
1148\begin{methoddesc}[file]{read}{\optional{size}}
1149 Read at most \var{size} bytes from the file (less if the read hits
Fred Drakef4cbada1999-04-14 14:31:53 +00001150 \EOF{} before obtaining \var{size} bytes). If the \var{size}
1151 argument is negative or omitted, read all data until \EOF{} is
1152 reached. The bytes are returned as a string object. An empty
1153 string is returned when \EOF{} is encountered immediately. (For
1154 certain files, like ttys, it makes sense to continue reading after
1155 an \EOF{} is hit.) Note that this method may call the underlying
1156 C function \cfunction{fread()} more than once in an effort to
1157 acquire as close to \var{size} bytes as possible.
Fred Drake64e3b431998-07-24 13:56:11 +00001158\end{methoddesc}
1159
1160\begin{methoddesc}[file]{readline}{\optional{size}}
1161 Read one entire line from the file. A trailing newline character is
Fred Drakeea003fc1999-04-05 21:59:15 +00001162 kept in the string\footnote{
Tim Peters8f01b682002-03-12 03:04:44 +00001163 The advantage of leaving the newline on is that an empty string
1164 can be returned to mean \EOF{} without being ambiguous. Another
1165 advantage is that (in cases where it might matter, for example. if you
1166 want to make an exact copy of a file while scanning its lines)
Fred Drake64e3b431998-07-24 13:56:11 +00001167 you can tell whether the last line of a file ended in a newline
Fred Drake4de96c22000-08-12 03:36:23 +00001168 or not (yes this happens!).
1169 } (but may be absent when a file ends with an
Fred Drake64e3b431998-07-24 13:56:11 +00001170 incomplete line). If the \var{size} argument is present and
1171 non-negative, it is a maximum byte count (including the trailing
1172 newline) and an incomplete line may be returned.
1173 An empty string is returned when \EOF{} is hit
Fred Drake0aa811c2001-10-20 04:24:09 +00001174 immediately. \note{Unlike \code{stdio}'s \cfunction{fgets()}, the
Fred Drake752ba392000-09-19 15:18:51 +00001175 returned string contains null characters (\code{'\e 0'}) if they
Fred Drake0aa811c2001-10-20 04:24:09 +00001176 occurred in the input.}
Fred Drake64e3b431998-07-24 13:56:11 +00001177\end{methoddesc}
1178
1179\begin{methoddesc}[file]{readlines}{\optional{sizehint}}
1180 Read until \EOF{} using \method{readline()} and return a list containing
1181 the lines thus read. If the optional \var{sizehint} argument is
Fred Drakec37b65e2001-11-28 07:26:15 +00001182 present, instead of reading up to \EOF, whole lines totalling
Fred Drake64e3b431998-07-24 13:56:11 +00001183 approximately \var{sizehint} bytes (possibly after rounding up to an
Fred Drake752ba392000-09-19 15:18:51 +00001184 internal buffer size) are read. Objects implementing a file-like
1185 interface may choose to ignore \var{sizehint} if it cannot be
1186 implemented, or cannot be implemented efficiently.
Fred Drake64e3b431998-07-24 13:56:11 +00001187\end{methoddesc}
1188
Guido van Rossum20ab9e92001-01-17 01:18:00 +00001189\begin{methoddesc}[file]{xreadlines}{}
Fred Drake82f93c62001-04-22 01:56:51 +00001190 Equivalent to
1191 \function{xreadlines.xreadlines(\var{file})}.\refstmodindex{xreadlines}
1192 (See the \refmodule{xreadlines} module for more information.)
1193 \versionadded{2.1}
Guido van Rossum20ab9e92001-01-17 01:18:00 +00001194\end{methoddesc}
1195
Fred Drake64e3b431998-07-24 13:56:11 +00001196\begin{methoddesc}[file]{seek}{offset\optional{, whence}}
1197 Set the file's current position, like \code{stdio}'s \cfunction{fseek()}.
1198 The \var{whence} argument is optional and defaults to \code{0}
1199 (absolute file positioning); other values are \code{1} (seek
1200 relative to the current position) and \code{2} (seek relative to the
Fred Drake19ae7832001-01-04 05:16:39 +00001201 file's end). There is no return value. Note that if the file is
1202 opened for appending (mode \code{'a'} or \code{'a+'}), any
1203 \method{seek()} operations will be undone at the next write. If the
1204 file is only opened for writing in append mode (mode \code{'a'}),
1205 this method is essentially a no-op, but it remains useful for files
1206 opened in append mode with reading enabled (mode \code{'a+'}).
Fred Drake64e3b431998-07-24 13:56:11 +00001207\end{methoddesc}
1208
1209\begin{methoddesc}[file]{tell}{}
1210 Return the file's current position, like \code{stdio}'s
1211 \cfunction{ftell()}.
1212\end{methoddesc}
1213
1214\begin{methoddesc}[file]{truncate}{\optional{size}}
Tim Peters8f01b682002-03-12 03:04:44 +00001215 Truncate the file's size. If the optional \var{size} argument is
Fred Drake752ba392000-09-19 15:18:51 +00001216 present, the file is truncated to (at most) that size. The size
Tim Peters8f01b682002-03-12 03:04:44 +00001217 defaults to the current position. The current file position is
1218 not changed. Note that if a specified size exceeds the file's
1219 current size, the result is platform-dependent: possibilities
1220 include that file may remain unchanged, increase to the specified
1221 size as if zero-filled, or increase to the specified size with
1222 undefined new content.
Tim Petersfb05db22002-03-11 00:24:00 +00001223 Availability: Windows, many \UNIX variants.
Fred Drake64e3b431998-07-24 13:56:11 +00001224\end{methoddesc}
1225
1226\begin{methoddesc}[file]{write}{str}
Fred Drake0aa811c2001-10-20 04:24:09 +00001227 Write a string to the file. There is no return value. Due to
Fred Drake3c48ef72001-01-09 22:47:46 +00001228 buffering, the string may not actually show up in the file until
1229 the \method{flush()} or \method{close()} method is called.
Fred Drake64e3b431998-07-24 13:56:11 +00001230\end{methoddesc}
1231
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001232\begin{methoddesc}[file]{writelines}{sequence}
1233 Write a sequence of strings to the file. The sequence can be any
1234 iterable object producing strings, typically a list of strings.
1235 There is no return value.
Fred Drake3c48ef72001-01-09 22:47:46 +00001236 (The name is intended to match \method{readlines()};
1237 \method{writelines()} does not add line separators.)
1238\end{methoddesc}
1239
Fred Drake64e3b431998-07-24 13:56:11 +00001240
Fred Drake038d2642001-09-22 04:34:48 +00001241Files support the iterator protocol. Each iteration returns the same
1242result as \code{\var{file}.readline()}, and iteration ends when the
1243\method{readline()} method returns an empty string.
1244
1245
Fred Drake752ba392000-09-19 15:18:51 +00001246File objects also offer a number of other interesting attributes.
1247These are not required for file-like objects, but should be
1248implemented if they make sense for the particular object.
Fred Drake64e3b431998-07-24 13:56:11 +00001249
1250\begin{memberdesc}[file]{closed}
Neal Norwitz6b353702002-04-09 18:15:00 +00001251bool indicating the current state of the file object. This is a
Fred Drake64e3b431998-07-24 13:56:11 +00001252read-only attribute; the \method{close()} method changes the value.
Fred Drake752ba392000-09-19 15:18:51 +00001253It may not be available on all file-like objects.
Fred Drake64e3b431998-07-24 13:56:11 +00001254\end{memberdesc}
1255
1256\begin{memberdesc}[file]{mode}
1257The I/O mode for the file. If the file was created using the
1258\function{open()} built-in function, this will be the value of the
Fred Drake752ba392000-09-19 15:18:51 +00001259\var{mode} parameter. This is a read-only attribute and may not be
1260present on all file-like objects.
Fred Drake64e3b431998-07-24 13:56:11 +00001261\end{memberdesc}
1262
1263\begin{memberdesc}[file]{name}
1264If the file object was created using \function{open()}, the name of
1265the file. Otherwise, some string that indicates the source of the
1266file object, of the form \samp{<\mbox{\ldots}>}. This is a read-only
Fred Drake752ba392000-09-19 15:18:51 +00001267attribute and may not be present on all file-like objects.
Fred Drake64e3b431998-07-24 13:56:11 +00001268\end{memberdesc}
1269
Barry Warsaw177b4a02002-05-22 20:39:43 +00001270\begin{memberdesc}[file]{newlines}
1271If Python was built with the \code{--with-universal-newlines} option
1272(the default) this read-only attribute exists, and for files opened in
1273universal newline read mode it keeps track of the types of newlines
1274encountered while reading the file. The values it can take are
1275\code{'\e r'}, \code{'\e n'}, \code{'\e r\e n'}, \code{None} (unknown,
1276no newlines read yet) or a tuple containing all the newline
1277types seen, to indicate that multiple
1278newline conventions were encountered. For files not opened in universal
1279newline read mode the value of this attribute will be \code{None}.
1280\end{memberdesc}
1281
Fred Drake64e3b431998-07-24 13:56:11 +00001282\begin{memberdesc}[file]{softspace}
1283Boolean that indicates whether a space character needs to be printed
1284before another value when using the \keyword{print} statement.
1285Classes that are trying to simulate a file object should also have a
1286writable \member{softspace} attribute, which should be initialized to
Fred Drake66571cc2000-09-09 03:30:34 +00001287zero. This will be automatic for most classes implemented in Python
1288(care may be needed for objects that override attribute access); types
1289implemented in C will have to provide a writable
1290\member{softspace} attribute.
Fred Drake0aa811c2001-10-20 04:24:09 +00001291\note{This attribute is not used to control the
Fred Drake51f53df2000-09-20 04:48:20 +00001292\keyword{print} statement, but to allow the implementation of
Fred Drake0aa811c2001-10-20 04:24:09 +00001293\keyword{print} to keep track of its internal state.}
Fred Drake64e3b431998-07-24 13:56:11 +00001294\end{memberdesc}
1295
Fred Drakea776cea2000-11-06 20:17:37 +00001296
Fred Drake99de2182001-10-30 06:23:14 +00001297\subsection{Other Built-in Types \label{typesother}}
1298
1299The interpreter supports several other kinds of objects.
1300Most of these support only one or two operations.
1301
1302
1303\subsubsection{Modules \label{typesmodules}}
1304
1305The only special operation on a module is attribute access:
1306\code{\var{m}.\var{name}}, where \var{m} is a module and \var{name}
1307accesses a name defined in \var{m}'s symbol table. Module attributes
1308can be assigned to. (Note that the \keyword{import} statement is not,
1309strictly speaking, an operation on a module object; \code{import
1310\var{foo}} does not require a module object named \var{foo} to exist,
1311rather it requires an (external) \emph{definition} for a module named
1312\var{foo} somewhere.)
1313
1314A special member of every module is \member{__dict__}.
1315This is the dictionary containing the module's symbol table.
1316Modifying this dictionary will actually change the module's symbol
1317table, but direct assignment to the \member{__dict__} attribute is not
1318possible (you can write \code{\var{m}.__dict__['a'] = 1}, which
1319defines \code{\var{m}.a} to be \code{1}, but you can't write
1320\code{\var{m}.__dict__ = \{\}}.
1321
1322Modules built into the interpreter are written like this:
1323\code{<module 'sys' (built-in)>}. If loaded from a file, they are
1324written as \code{<module 'os' from
1325'/usr/local/lib/python\shortversion/os.pyc'>}.
1326
1327
1328\subsubsection{Classes and Class Instances \label{typesobjects}}
1329\nodename{Classes and Instances}
1330
1331See chapters 3 and 7 of the \citetitle[../ref/ref.html]{Python
1332Reference Manual} for these.
1333
1334
1335\subsubsection{Functions \label{typesfunctions}}
1336
1337Function objects are created by function definitions. The only
1338operation on a function object is to call it:
1339\code{\var{func}(\var{argument-list})}.
1340
1341There are really two flavors of function objects: built-in functions
1342and user-defined functions. Both support the same operation (to call
1343the function), but the implementation is different, hence the
1344different object types.
1345
1346The implementation adds two special read-only attributes:
1347\code{\var{f}.func_code} is a function's \dfn{code
1348object}\obindex{code} (see below) and \code{\var{f}.func_globals} is
1349the dictionary used as the function's global namespace (this is the
1350same as \code{\var{m}.__dict__} where \var{m} is the module in which
1351the function \var{f} was defined).
1352
1353Function objects also support getting and setting arbitrary
1354attributes, which can be used to, e.g. attach metadata to functions.
1355Regular attribute dot-notation is used to get and set such
1356attributes. \emph{Note that the current implementation only supports
1357function attributes on user-defined functions. Function attributes on
1358built-in functions may be supported in the future.}
1359
1360Functions have another special attribute \code{\var{f}.__dict__}
1361(a.k.a. \code{\var{f}.func_dict}) which contains the namespace used to
1362support function attributes. \code{__dict__} and \code{func_dict} can
1363be accessed directly or set to a dictionary object. A function's
1364dictionary cannot be deleted.
1365
1366\subsubsection{Methods \label{typesmethods}}
1367\obindex{method}
1368
1369Methods are functions that are called using the attribute notation.
1370There are two flavors: built-in methods (such as \method{append()} on
1371lists) and class instance methods. Built-in methods are described
1372with the types that support them.
1373
1374The implementation adds two special read-only attributes to class
1375instance methods: \code{\var{m}.im_self} is the object on which the
1376method operates, and \code{\var{m}.im_func} is the function
1377implementing the method. Calling \code{\var{m}(\var{arg-1},
1378\var{arg-2}, \textrm{\ldots}, \var{arg-n})} is completely equivalent to
1379calling \code{\var{m}.im_func(\var{m}.im_self, \var{arg-1},
1380\var{arg-2}, \textrm{\ldots}, \var{arg-n})}.
1381
1382Class instance methods are either \emph{bound} or \emph{unbound},
1383referring to whether the method was accessed through an instance or a
1384class, respectively. When a method is unbound, its \code{im_self}
1385attribute will be \code{None} and if called, an explicit \code{self}
1386object must be passed as the first argument. In this case,
1387\code{self} must be an instance of the unbound method's class (or a
1388subclass of that class), otherwise a \code{TypeError} is raised.
1389
1390Like function objects, methods objects support getting
1391arbitrary attributes. However, since method attributes are actually
1392stored on the underlying function object (\code{meth.im_func}),
1393setting method attributes on either bound or unbound methods is
1394disallowed. Attempting to set a method attribute results in a
1395\code{TypeError} being raised. In order to set a method attribute,
1396you need to explicitly set it on the underlying function object:
1397
1398\begin{verbatim}
1399class C:
1400 def method(self):
1401 pass
1402
1403c = C()
1404c.method.im_func.whoami = 'my name is c'
1405\end{verbatim}
1406
1407See the \citetitle[../ref/ref.html]{Python Reference Manual} for more
1408information.
1409
1410
1411\subsubsection{Code Objects \label{bltin-code-objects}}
1412\obindex{code}
1413
1414Code objects are used by the implementation to represent
1415``pseudo-compiled'' executable Python code such as a function body.
1416They differ from function objects because they don't contain a
1417reference to their global execution environment. Code objects are
1418returned by the built-in \function{compile()} function and can be
1419extracted from function objects through their \member{func_code}
1420attribute.
1421\bifuncindex{compile}
1422\withsubitem{(function object attribute)}{\ttindex{func_code}}
1423
1424A code object can be executed or evaluated by passing it (instead of a
1425source string) to the \keyword{exec} statement or the built-in
1426\function{eval()} function.
1427\stindex{exec}
1428\bifuncindex{eval}
1429
1430See the \citetitle[../ref/ref.html]{Python Reference Manual} for more
1431information.
1432
1433
1434\subsubsection{Type Objects \label{bltin-type-objects}}
1435
1436Type objects represent the various object types. An object's type is
1437accessed by the built-in function \function{type()}. There are no special
1438operations on types. The standard module \module{types} defines names
1439for all standard built-in types.
1440\bifuncindex{type}
1441\refstmodindex{types}
1442
1443Types are written like this: \code{<type 'int'>}.
1444
1445
1446\subsubsection{The Null Object \label{bltin-null-object}}
1447
1448This object is returned by functions that don't explicitly return a
1449value. It supports no special operations. There is exactly one null
1450object, named \code{None} (a built-in name).
1451
1452It is written as \code{None}.
1453
1454
1455\subsubsection{The Ellipsis Object \label{bltin-ellipsis-object}}
1456
1457This object is used by extended slice notation (see the
1458\citetitle[../ref/ref.html]{Python Reference Manual}). It supports no
1459special operations. There is exactly one ellipsis object, named
1460\constant{Ellipsis} (a built-in name).
1461
1462It is written as \code{Ellipsis}.
1463
Guido van Rossum77f6a652002-04-03 22:41:51 +00001464\subsubsection{Boolean Values}
1465
1466Boolean values are the two constant objects \code{False} and
1467\code{True}. They are used to represent truth values (although other
1468values can also be considered false or true). In numeric contexts
1469(for example when used as the argument to an arithmetic operator),
1470they behave like the integers 0 and 1, respectively. The built-in
1471function \function{bool()} can be used to cast any value to a Boolean,
1472if the value can be interpreted as a truth value (see section Truth
1473Value Testing above).
1474
1475They are written as \code{False} and \code{True}, respectively.
1476\index{False}
1477\index{True}
1478\indexii{Boolean}{values}
1479
Fred Drake99de2182001-10-30 06:23:14 +00001480
Fred Drake9474d861999-02-12 22:05:33 +00001481\subsubsection{Internal Objects \label{typesinternal}}
Fred Drake64e3b431998-07-24 13:56:11 +00001482
Fred Drake37f15741999-11-10 16:21:37 +00001483See the \citetitle[../ref/ref.html]{Python Reference Manual} for this
Fred Drake512bb722000-08-18 03:12:38 +00001484information. It describes stack frame objects, traceback objects, and
1485slice objects.
Fred Drake64e3b431998-07-24 13:56:11 +00001486
1487
Fred Drake7a2f0661998-09-10 18:25:58 +00001488\subsection{Special Attributes \label{specialattrs}}
Fred Drake64e3b431998-07-24 13:56:11 +00001489
1490The implementation adds a few special read-only attributes to several
1491object types, where they are relevant:
1492
Fred Drakea776cea2000-11-06 20:17:37 +00001493\begin{memberdesc}[object]{__dict__}
1494A dictionary or other mapping object used to store an
Fred Drake7a2f0661998-09-10 18:25:58 +00001495object's (writable) attributes.
Fred Drakea776cea2000-11-06 20:17:37 +00001496\end{memberdesc}
Fred Drake64e3b431998-07-24 13:56:11 +00001497
Fred Drakea776cea2000-11-06 20:17:37 +00001498\begin{memberdesc}[object]{__methods__}
Fred Drake35705512001-12-03 17:32:27 +00001499\deprecated{2.2}{Use the built-in function \function{dir()} to get a
1500list of an object's attributes. This attribute is no longer available.}
Fred Drakea776cea2000-11-06 20:17:37 +00001501\end{memberdesc}
Fred Drake64e3b431998-07-24 13:56:11 +00001502
Fred Drakea776cea2000-11-06 20:17:37 +00001503\begin{memberdesc}[object]{__members__}
Fred Drake35705512001-12-03 17:32:27 +00001504\deprecated{2.2}{Use the built-in function \function{dir()} to get a
1505list of an object's attributes. This attribute is no longer available.}
Fred Drakea776cea2000-11-06 20:17:37 +00001506\end{memberdesc}
Fred Drake64e3b431998-07-24 13:56:11 +00001507
Fred Drakea776cea2000-11-06 20:17:37 +00001508\begin{memberdesc}[instance]{__class__}
Fred Drake7a2f0661998-09-10 18:25:58 +00001509The class to which a class instance belongs.
Fred Drakea776cea2000-11-06 20:17:37 +00001510\end{memberdesc}
Fred Drake64e3b431998-07-24 13:56:11 +00001511
Fred Drakea776cea2000-11-06 20:17:37 +00001512\begin{memberdesc}[class]{__bases__}
Fred Drake907e76b2001-07-06 20:30:11 +00001513The tuple of base classes of a class object. If there are no base
1514classes, this will be an empty tuple.
Fred Drakea776cea2000-11-06 20:17:37 +00001515\end{memberdesc}