Rietveld Code Review Tool
Help | Bug tracker | Discussion group | Source code | Sign in
(31703)

Delta Between Two Patch Sets: Doc/library/stdtypes.rst

Issue 11373: Fix 2 new typos in the docs
Left Patch Set: Created 8 years, 3 months ago
Right Patch Set: Created 8 years, 3 months ago
Left:
Right:
Use n/p to move between diff chunks; N/P to move between comments. Please Sign in to add in-line comments.
Jump to:
Left: Side by side diff | Download
Right: Side by side diff | Download
« no previous file with change/comment | « no previous file | no next file » | no next file with change/comment »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
LEFTRIGHT
1 .. XXX: reference/datamodel and this have quite a few overlaps! 1 .. XXX: reference/datamodel and this have quite a few overlaps!
2 2
3 3
4 .. _bltin-types: 4 .. _bltin-types:
5 5
6 ************** 6 **************
7 Built-in Types 7 Built-in Types
8 ************** 8 **************
9 9
10 The following sections describe the standard types that are built into the 10 The following sections describe the standard types that are built into the
11 interpreter. 11 interpreter.
12 12
13 .. note::
14
15 Historically (until release 2.2), Python's built-in types have differed from
16 user-defined types because it was not possible to use the built-in types as t he
17 basis for object-oriented inheritance. This limitation no longer
18 exists.
19
20 .. index:: pair: built-in; types 13 .. index:: pair: built-in; types
21 14
22 The principal built-in types are numerics, sequences, mappings, files, classes, 15 The principal built-in types are numerics, sequences, mappings, classes,
23 instances and exceptions. 16 instances and exceptions.
24
25 .. index:: statement: print
26 17
27 Some operations are supported by several object types; in particular, 18 Some operations are supported by several object types; in particular,
28 practically all objects can be compared, tested for truth value, and converted 19 practically all objects can be compared, tested for truth value, and converted
29 to a string (with the :func:`repr` function or the slightly different 20 to a string (with the :func:`repr` function or the slightly different
30 :func:`str` function). The latter function is implicitly used when an object is 21 :func:`str` function). The latter function is implicitly used when an object is
31 written by the :func:`print` function. 22 written by the :func:`print` function.
32 23
33 24
34 .. _truth: 25 .. _truth:
35 26
(...skipping 12 matching lines...) Expand all
48 following values are considered false: 39 following values are considered false:
49 40
50 .. index:: single: None (Built-in object) 41 .. index:: single: None (Built-in object)
51 42
52 * ``None`` 43 * ``None``
53 44
54 .. index:: single: False (Built-in object) 45 .. index:: single: False (Built-in object)
55 46
56 * ``False`` 47 * ``False``
57 48
58 * zero of any numeric type, for example, ``0``, ``0L``, ``0.0``, ``0j``. 49 * zero of any numeric type, for example, ``0``, ``0.0``, ``0j``.
59 50
60 * any empty sequence, for example, ``''``, ``()``, ``[]``. 51 * any empty sequence, for example, ``''``, ``()``, ``[]``.
61 52
62 * any empty mapping, for example, ``{}``. 53 * any empty mapping, for example, ``{}``.
63 54
64 * instances of user-defined classes, if the class defines a :meth:`__nonzero__` 55 * instances of user-defined classes, if the class defines a :meth:`__bool__` or
65 or :meth:`__len__` method, when that method returns the integer zero or 56 :meth:`__len__` method, when that method returns the integer zero or
66 :class:`bool` value ``False``. [#]_ 57 :class:`bool` value ``False``. [#]_
67 58
68 .. index:: single: true 59 .. index:: single: true
69 60
70 All other values are considered true --- so objects of many types are always 61 All other values are considered true --- so objects of many types are always
71 true. 62 true.
72 63
73 .. index:: 64 .. index::
74 operator: or 65 operator: or
75 operator: and 66 operator: and
(...skipping 58 matching lines...) Expand 10 before | Expand all | Expand 10 after
134 pair: operator; comparison 125 pair: operator; comparison
135 operator: == 126 operator: ==
136 operator: < 127 operator: <
137 operator: <= 128 operator: <=
138 operator: > 129 operator: >
139 operator: >= 130 operator: >=
140 operator: != 131 operator: !=
141 operator: is 132 operator: is
142 operator: is not 133 operator: is not
143 134
144 Comparison operations are supported by all objects. They all have the same 135 There are eight comparison operations in Python. They all have the same
145 priority (which is higher than that of the Boolean operations). Comparisons can 136 priority (which is higher than that of the Boolean operations). Comparisons can
146 be chained arbitrarily; for example, ``x < y <= z`` is equivalent to ``x < y and 137 be chained arbitrarily; for example, ``x < y <= z`` is equivalent to ``x < y and
147 y <= z``, except that *y* is evaluated only once (but in both cases *z* is not 138 y <= z``, except that *y* is evaluated only once (but in both cases *z* is not
148 evaluated at all when ``x < y`` is found to be false). 139 evaluated at all when ``x < y`` is found to be false).
149 140
150 This table summarizes the comparison operations: 141 This table summarizes the comparison operations:
151 142
152 +------------+-------------------------+-------+ 143 +------------+-------------------------+
153 | Operation | Meaning | Notes | 144 | Operation | Meaning |
154 +============+=========================+=======+ 145 +============+=========================+
155 | ``<`` | strictly less than | | 146 | ``<`` | strictly less than |
156 +------------+-------------------------+-------+ 147 +------------+-------------------------+
157 | ``<=`` | less than or equal | | 148 | ``<=`` | less than or equal |
158 +------------+-------------------------+-------+ 149 +------------+-------------------------+
159 | ``>`` | strictly greater than | | 150 | ``>`` | strictly greater than |
160 +------------+-------------------------+-------+ 151 +------------+-------------------------+
161 | ``>=`` | greater than or equal | | 152 | ``>=`` | greater than or equal |
162 +------------+-------------------------+-------+ 153 +------------+-------------------------+
163 | ``==`` | equal | | 154 | ``==`` | equal |
164 +------------+-------------------------+-------+ 155 +------------+-------------------------+
165 | ``!=`` | not equal | \(1) | 156 | ``!=`` | not equal |
166 +------------+-------------------------+-------+ 157 +------------+-------------------------+
167 | ``is`` | object identity | | 158 | ``is`` | object identity |
168 +------------+-------------------------+-------+ 159 +------------+-------------------------+
169 | ``is not`` | negated object identity | | 160 | ``is not`` | negated object identity |
170 +------------+-------------------------+-------+ 161 +------------+-------------------------+
171
172 Notes:
173
174 (1)
175 ``!=`` can also be written ``<>``, but this is an obsolete usage
176 kept for backwards compatibility only. New code should always use
177 ``!=``.
178 162
179 .. index:: 163 .. index::
180 pair: object; numeric 164 pair: object; numeric
181 pair: objects; comparing 165 pair: objects; comparing
182 166
183 Objects of different types, except different numeric types and different string 167 Objects of different types, except different numeric types, never compare equal.
184 types, never compare equal; such objects are ordered consistently but 168 Furthermore, some types (for example, function objects) support only a degenerat e
185 arbitrarily (so that sorting a heterogeneous array yields a consistent result). 169 notion of comparison where any two objects of that type are unequal. The ``<``,
186 Furthermore, some types (for example, file objects) support only a degenerate 170 ``<=``, ``>`` and ``>=`` operators will raise a :exc:`TypeError` exception when
187 notion of comparison where any two objects of that type are unequal. Again, 171 comparing a complex number with another built-in numeric type, when the objects
188 such objects are ordered arbitrarily but consistently. The ``<``, ``<=``, ``>`` 172 are of different types that cannot be compared, or in other cases where there is
189 and ``>=`` operators will raise a :exc:`TypeError` exception when any operand is 173 no defined ordering.
190 a complex number. 174
191 175 .. index::
192 .. index:: single: __cmp__() (instance method) 176 single: __eq__() (instance method)
193 177 single: __ne__() (instance method)
194 Instances of a class normally compare as non-equal unless the class defines the 178 single: __lt__() (instance method)
195 :meth:`__cmp__` method. Refer to :ref:`customization`) for information on the 179 single: __le__() (instance method)
196 use of this method to effect object comparisons. 180 single: __gt__() (instance method)
197 181 single: __ge__() (instance method)
198 .. impl-detail:: 182
199 183 Non-identical instances of a class normally compare as non-equal unless the
200 Objects of different types except numbers are ordered by their type names; 184 class defines the :meth:`__eq__` method.
201 objects of the same types that don't support proper comparison are ordered by 185
202 their address. 186 Instances of a class cannot be ordered with respect to other instances of the
187 same class, or other types of object, unless the class defines enough of the
188 methods :meth:`__lt__`, :meth:`__le__`, :meth:`__gt__`, and :meth:`__ge__` (in
189 general, :meth:`__lt__` and :meth:`__eq__` are sufficient, if you want the
190 conventional meanings of the comparison operators).
191
192 The behavior of the :keyword:`is` and :keyword:`is not` operators cannot be
193 customized; also they can be applied to any two objects and never raise an
194 exception.
203 195
204 .. index:: 196 .. index::
205 operator: in 197 operator: in
206 operator: not in 198 operator: not in
207 199
208 Two more operations with the same syntactic priority, ``in`` and ``not in``, are 200 Two more operations with the same syntactic priority, :keyword:`in` and
209 supported only by sequence types (below). 201 :keyword:`not in`, are supported only by sequence types (below).
210 202
211 203
212 .. _typesnumeric: 204 .. _typesnumeric:
213 205
214 Numeric Types --- :class:`int`, :class:`float`, :class:`long`, :class:`complex` 206 Numeric Types --- :class:`int`, :class:`float`, :class:`complex`
215 =============================================================================== 207 ================================================================
216 208
217 .. index:: 209 .. index::
218 object: numeric 210 object: numeric
219 object: Boolean 211 object: Boolean
220 object: integer 212 object: integer
221 object: long integer
222 object: floating point 213 object: floating point
223 object: complex number 214 object: complex number
224 pair: C; language 215 pair: C; language
225 216
226 There are four distinct numeric types: :dfn:`plain integers`, :dfn:`long 217 There are three distinct numeric types: :dfn:`integers`, :dfn:`floating
227 integers`, :dfn:`floating point numbers`, and :dfn:`complex numbers`. In 218 point numbers`, and :dfn:`complex numbers`. In addition, Booleans are a
228 addition, Booleans are a subtype of plain integers. Plain integers (also just 219 subtype of integers. Integers have unlimited precision. Floating point
229 called :dfn:`integers`) are implemented using :ctype:`long` in C, which gives 220 numbers are usually implemented using :c:type:`double` in C; information
230 them at least 32 bits of precision (``sys.maxint`` is always set to the maximum 221 about the precision and internal representation of floating point
231 plain integer value for the current platform, the minimum value is 222 numbers for the machine on which your program is running is available
232 ``-sys.maxint - 1``). Long integers have unlimited precision. Floating point 223 in :data:`sys.float_info`. Complex numbers have a real and imaginary
233 numbers are usually implemented using :ctype:`double` in C; information about 224 part, which are each a floating point number. To extract these parts
234 the precision and internal representation of floating point numbers for the 225 from a complex number *z*, use ``z.real`` and ``z.imag``. (The standard
235 machine on which your program is running is available in 226 library includes additional numeric types, :mod:`fractions` that hold
236 :data:`sys.float_info`. Complex numbers have a real and imaginary part, which 227 rationals, and :mod:`decimal` that hold floating-point numbers with
237 are each a floating point number. To extract these parts from a complex number 228 user-definable precision.)
238 *z*, use ``z.real`` and ``z.imag``. (The standard library includes additional
239 numeric types, :mod:`fractions` that hold rationals, and :mod:`decimal` that
240 hold floating-point numbers with user-definable precision.)
241 229
242 .. index:: 230 .. index::
243 pair: numeric; literals 231 pair: numeric; literals
244 pair: integer; literals 232 pair: integer; literals
245 triple: long; integer; literals
246 pair: floating point; literals 233 pair: floating point; literals
247 pair: complex number; literals 234 pair: complex number; literals
248 pair: hexadecimal; literals 235 pair: hexadecimal; literals
249 pair: octal; literals 236 pair: octal; literals
237 pair: binary; literals
250 238
251 Numbers are created by numeric literals or as the result of built-in functions 239 Numbers are created by numeric literals or as the result of built-in functions
252 and operators. Unadorned integer literals (including binary, hex, and octal 240 and operators. Unadorned integer literals (including hex, octal and binary
253 numbers) yield plain integers unless the value they denote is too large to be 241 numbers) yield integers. Numeric literals containing a decimal point or an
254 represented as a plain integer, in which case they yield a long integer. 242 exponent sign yield floating point numbers. Appending ``'j'`` or ``'J'`` to a
255 Integer literals with an ``'L'`` or ``'l'`` suffix yield long integers (``'L'`` 243 numeric literal yields an imaginary number (a complex number with a zero real
256 is preferred because ``1l`` looks too much like eleven!). Numeric literals 244 part) which you can add to an integer or float to get a complex number with real
257 containing a decimal point or an exponent sign yield floating point numbers. 245 and imaginary parts.
258 Appending ``'j'`` or ``'J'`` to a numeric literal yields a complex number with a
259 zero real part. A complex numeric literal is the sum of a real and an imaginary
260 part.
261 246
262 .. index:: 247 .. index::
263 single: arithmetic 248 single: arithmetic
264 builtin: int 249 builtin: int
265 builtin: long
266 builtin: float 250 builtin: float
267 builtin: complex 251 builtin: complex
268 operator: + 252 operator: +
269 operator: - 253 operator: -
270 operator: * 254 operator: *
271 operator: / 255 operator: /
272 operator: // 256 operator: //
273 operator: % 257 operator: %
274 operator: ** 258 operator: **
275 259
276 Python fully supports mixed arithmetic: when a binary arithmetic operator has 260 Python fully supports mixed arithmetic: when a binary arithmetic operator has
277 operands of different numeric types, the operand with the "narrower" type is 261 operands of different numeric types, the operand with the "narrower" type is
278 widened to that of the other, where plain integer is narrower than long integer 262 widened to that of the other, where integer is narrower than floating point,
279 is narrower than floating point is narrower than complex. Comparisons between 263 which is narrower than complex. Comparisons between numbers of mixed type use
280 numbers of mixed type use the same rule. [#]_ The constructors :func:`int`, 264 the same rule. [#]_ The constructors :func:`int`, :func:`float`, and
281 :func:`long`, :func:`float`, and :func:`complex` can be used to produce numbers 265 :func:`complex` can be used to produce numbers of a specific type.
282 of a specific type. 266
283 267 All numeric types (except complex) support the following operations, sorted by
284 All built-in numeric types support the following operations. See 268 ascending priority (operations in the same box have the same priority; all
285 :ref:`power` and later sections for the operators' priorities. 269 numeric operations have a higher priority than comparison operations):
286 270
287 +--------------------+---------------------------------+--------+ 271 +---------------------+---------------------------------+-------+--------------- -----+
288 | Operation | Result | Notes | 272 | Operation | Result | Notes | Full documenta tion |
289 +====================+=================================+========+ 273 +=====================+=================================+=======+=============== =====+
290 | ``x + y`` | sum of *x* and *y* | | 274 | ``x + y`` | sum of *x* and *y* | | |
291 +--------------------+---------------------------------+--------+ 275 +---------------------+---------------------------------+-------+--------------- -----+
292 | ``x - y`` | difference of *x* and *y* | | 276 | ``x - y`` | difference of *x* and *y* | | |
293 +--------------------+---------------------------------+--------+ 277 +---------------------+---------------------------------+-------+--------------- -----+
294 | ``x * y`` | product of *x* and *y* | | 278 | ``x * y`` | product of *x* and *y* | | |
295 +--------------------+---------------------------------+--------+ 279 +---------------------+---------------------------------+-------+--------------- -----+
296 | ``x / y`` | quotient of *x* and *y* | \(1) | 280 | ``x / y`` | quotient of *x* and *y* | | |
297 +--------------------+---------------------------------+--------+ 281 +---------------------+---------------------------------+-------+--------------- -----+
298 | ``x // y`` | (floored) quotient of *x* and | (4)(5) | 282 | ``x // y`` | floored quotient of *x* and | \(1) | |
299 | | *y* | | 283 | | *y* | | |
300 +--------------------+---------------------------------+--------+ 284 +---------------------+---------------------------------+-------+--------------- -----+
301 | ``x % y`` | remainder of ``x / y`` | \(4) | 285 | ``x % y`` | remainder of ``x / y`` | \(2) | |
302 +--------------------+---------------------------------+--------+ 286 +---------------------+---------------------------------+-------+--------------- -----+
303 | ``-x`` | *x* negated | | 287 | ``-x`` | *x* negated | | |
304 +--------------------+---------------------------------+--------+ 288 +---------------------+---------------------------------+-------+--------------- -----+
305 | ``+x`` | *x* unchanged | | 289 | ``+x`` | *x* unchanged | | |
306 +--------------------+---------------------------------+--------+ 290 +---------------------+---------------------------------+-------+--------------- -----+
307 | ``abs(x)`` | absolute value or magnitude of | \(3) | 291 | ``abs(x)`` | absolute value or magnitude of | | :func:`abs` |
308 | | *x* | | 292 | | *x* | | |
309 +--------------------+---------------------------------+--------+ 293 +---------------------+---------------------------------+-------+--------------- -----+
310 | ``int(x)`` | *x* converted to integer | \(2) | 294 | ``int(x)`` | *x* converted to integer | \(3) | :func:`int` |
311 +--------------------+---------------------------------+--------+ 295 +---------------------+---------------------------------+-------+--------------- -----+
312 | ``long(x)`` | *x* converted to long integer | \(2) | 296 | ``float(x)`` | *x* converted to floating point | \(4) | :func:`float` |
313 +--------------------+---------------------------------+--------+ 297 +---------------------+---------------------------------+-------+--------------- -----+
314 | ``float(x)`` | *x* converted to floating point | \(6) | 298 | ``complex(re, im)`` | a complex number with real part | | :func:`complex ` |
315 +--------------------+---------------------------------+--------+ 299 | | *re*, imaginary part *im*. | | |
316 | ``complex(re,im)`` | a complex number with real part | | 300 | | *im* defaults to zero. | | |
317 | | *re*, imaginary part *im*. | | 301 +---------------------+---------------------------------+-------+--------------- -----+
318 | | *im* defaults to zero. | | 302 | ``c.conjugate()`` | conjugate of the complex number | | |
319 +--------------------+---------------------------------+--------+ 303 | | *c* | | |
320 | ``c.conjugate()`` | conjugate of the complex number | | 304 +---------------------+---------------------------------+-------+--------------- -----+
321 | | *c*. (Identity on real numbers) | | 305 | ``divmod(x, y)`` | the pair ``(x // y, x % y)`` | \(2) | :func:`divmod` |
322 +--------------------+---------------------------------+--------+ 306 +---------------------+---------------------------------+-------+--------------- -----+
323 | ``divmod(x, y)`` | the pair ``(x // y, x % y)`` | (3)(4) | 307 | ``pow(x, y)`` | *x* to the power *y* | \(5) | :func:`pow` |
324 +--------------------+---------------------------------+--------+ 308 +---------------------+---------------------------------+-------+--------------- -----+
325 | ``pow(x, y)`` | *x* to the power *y* | (3)(7) | 309 | ``x ** y`` | *x* to the power *y* | \(5) | |
326 +--------------------+---------------------------------+--------+ 310 +---------------------+---------------------------------+-------+--------------- -----+
327 | ``x ** y`` | *x* to the power *y* | \(7) |
328 +--------------------+---------------------------------+--------+
329 311
330 .. index:: 312 .. index::
331 triple: operations on; numeric; types 313 triple: operations on; numeric; types
332 single: conjugate() (complex number method) 314 single: conjugate() (complex number method)
333 315
334 Notes: 316 Notes:
335 317
336 (1) 318 (1)
337 .. index:: 319 Also referred to as integer division. The resultant value is a whole
338 pair: integer; division 320 integer, though the result's type is not necessarily int. The result is
339 triple: long; integer; division 321 always rounded towards minus infinity: ``1//2`` is ``0``, ``(-1)//2`` is
340 322 ``-1``, ``1//(-2)`` is ``-1``, and ``(-1)//(-2)`` is ``0``.
341 For (plain or long) integer division, the result is an integer. The result is
342 always rounded towards minus infinity: 1/2 is 0, (-1)/2 is -1, 1/(-2) is -1, and
343 (-1)/(-2) is 0. Note that the result is a long integer if either operand is a
344 long integer, regardless of the numeric value.
345 323
346 (2) 324 (2)
325 Not for complex numbers. Instead convert to floats using :func:`abs` if
326 appropriate.
327
328 (3)
347 .. index:: 329 .. index::
348 module: math 330 module: math
349 single: floor() (in module math) 331 single: floor() (in module math)
350 single: ceil() (in module math) 332 single: ceil() (in module math)
351 single: trunc() (in module math) 333 single: trunc() (in module math)
352 pair: numeric; conversions 334 pair: numeric; conversions
353 335 pair: C; language
354 Conversion from floats using :func:`int` or :func:`long` truncates toward 336
355 zero like the related function, :func:`math.trunc`. Use the function 337 Conversion from floating point to integer may round or truncate
356 :func:`math.floor` to round downward and :func:`math.ceil` to round 338 as in C; see functions :func:`floor` and :func:`ceil` in the :mod:`math` modu le
357 upward. 339 for well-defined conversions.
358
359 (3)
360 See :ref:`built-in-funcs` for a full description.
361 340
362 (4) 341 (4)
363 .. deprecated:: 2.3
364 The floor division operator, the modulo operator, and the :func:`divmod`
365 function are no longer defined for complex numbers. Instead, convert to
366 a floating point number using the :func:`abs` function if appropriate.
367
368 (5)
369 Also referred to as integer division. The resultant value is a whole integer ,
370 though the result's type is not necessarily int.
371
372 (6)
373 float also accepts the strings "nan" and "inf" with an optional prefix "+" 342 float also accepts the strings "nan" and "inf" with an optional prefix "+"
374 or "-" for Not a Number (NaN) and positive or negative infinity. 343 or "-" for Not a Number (NaN) and positive or negative infinity.
375 344
376 .. versionadded:: 2.6 345 (5)
377
378 (7)
379 Python defines ``pow(0, 0)`` and ``0 ** 0`` to be ``1``, as is common for 346 Python defines ``pow(0, 0)`` and ``0 ** 0`` to be ``1``, as is common for
380 programming languages. 347 programming languages.
381 348
382 All :class:`numbers.Real` types (:class:`int`, :class:`long`, and 349
350
351 All :class:`numbers.Real` types (:class:`int` and
383 :class:`float`) also include the following operations: 352 :class:`float`) also include the following operations:
384 353
385 +--------------------+------------------------------------+--------+ 354 +--------------------+------------------------------------+--------+
386 | Operation | Result | Notes | 355 | Operation | Result | Notes |
387 +====================+====================================+========+ 356 +====================+====================================+========+
388 | ``math.trunc(x)`` | *x* truncated to Integral | | 357 | ``math.trunc(x)`` | *x* truncated to Integral | |
389 +--------------------+------------------------------------+--------+ 358 +--------------------+------------------------------------+--------+
390 | ``round(x[, n])`` | *x* rounded to n digits, | | 359 | ``round(x[, n])`` | *x* rounded to n digits, | |
391 | | rounding half to even. If n is | | 360 | | rounding half to even. If n is | |
392 | | omitted, it defaults to 0. | | 361 | | omitted, it defaults to 0. | |
393 +--------------------+------------------------------------+--------+ 362 +--------------------+------------------------------------+--------+
394 | ``math.floor(x)`` | the greatest integral float <= *x* | | 363 | ``math.floor(x)`` | the greatest integral float <= *x* | |
395 +--------------------+------------------------------------+--------+ 364 +--------------------+------------------------------------+--------+
396 | ``math.ceil(x)`` | the least integral float >= *x* | | 365 | ``math.ceil(x)`` | the least integral float >= *x* | |
397 +--------------------+------------------------------------+--------+ 366 +--------------------+------------------------------------+--------+
398 367
368 For additional numeric operations see the :mod:`math` and :mod:`cmath`
369 modules.
370
399 .. XXXJH exceptions: overflow (when? what operations?) zerodivision 371 .. XXXJH exceptions: overflow (when? what operations?) zerodivision
400 372
401 373
402 .. _bitstring-ops: 374 .. _bitstring-ops:
403 375
404 Bit-string Operations on Integer Types 376 Bit-string Operations on Integer Types
405 -------------------------------------- 377 --------------------------------------
406 378
407 .. index:: 379 .. index::
408 triple: operations on; integer; types 380 triple: operations on; integer; types
409 pair: bit-string; operations 381 pair: bit-string; operations
410 pair: shifting; operations 382 pair: shifting; operations
411 pair: masking; operations 383 pair: masking; operations
412 operator: ^ 384 operator: ^
413 operator: & 385 operator: &
414 operator: << 386 operator: <<
415 operator: >> 387 operator: >>
416 388
417 Plain and long integer types support additional operations that make sense only 389 Integers support additional operations that make sense only for bit-strings.
418 for bit-strings. Negative numbers are treated as their 2's complement value 390 Negative numbers are treated as their 2's complement value (this assumes a
419 (for long integers, this assumes a sufficiently large number of bits that no 391 sufficiently large number of bits that no overflow occurs during the operation).
420 overflow occurs during the operation).
421 392
422 The priorities of the binary bitwise operations are all lower than the numeric 393 The priorities of the binary bitwise operations are all lower than the numeric
423 operations and higher than the comparisons; the unary operation ``~`` has the 394 operations and higher than the comparisons; the unary operation ``~`` has the
424 same priority as the other unary numeric operations (``+`` and ``-``). 395 same priority as the other unary numeric operations (``+`` and ``-``).
425 396
426 This table lists the bit-string operations sorted in ascending priority: 397 This table lists the bit-string operations sorted in ascending priority
398 (operations in the same box have the same priority):
427 399
428 +------------+--------------------------------+----------+ 400 +------------+--------------------------------+----------+
429 | Operation | Result | Notes | 401 | Operation | Result | Notes |
430 +============+================================+==========+ 402 +============+================================+==========+
431 | ``x | y`` | bitwise :dfn:`or` of *x* and | | 403 | ``x | y`` | bitwise :dfn:`or` of *x* and | |
432 | | *y* | | 404 | | *y* | |
433 +------------+--------------------------------+----------+ 405 +------------+--------------------------------+----------+
434 | ``x ^ y`` | bitwise :dfn:`exclusive or` of | | 406 | ``x ^ y`` | bitwise :dfn:`exclusive or` of | |
435 | | *x* and *y* | | 407 | | *x* and *y* | |
436 +------------+--------------------------------+----------+ 408 +------------+--------------------------------+----------+
437 | ``x & y`` | bitwise :dfn:`and` of *x* and | | 409 | ``x & y`` | bitwise :dfn:`and` of *x* and | |
438 | | *y* | | 410 | | *y* | |
439 +------------+--------------------------------+----------+ 411 +------------+--------------------------------+----------+
440 | ``x << n`` | *x* shifted left by *n* bits | (1)(2) | 412 | ``x << n`` | *x* shifted left by *n* bits | (1)(2) |
441 +------------+--------------------------------+----------+ 413 +------------+--------------------------------+----------+
442 | ``x >> n`` | *x* shifted right by *n* bits | (1)(3) | 414 | ``x >> n`` | *x* shifted right by *n* bits | (1)(3) |
443 +------------+--------------------------------+----------+ 415 +------------+--------------------------------+----------+
444 | ``~x`` | the bits of *x* inverted | | 416 | ``~x`` | the bits of *x* inverted | |
445 +------------+--------------------------------+----------+ 417 +------------+--------------------------------+----------+
446 418
447 Notes: 419 Notes:
448 420
449 (1) 421 (1)
450 Negative shift counts are illegal and cause a :exc:`ValueError` to be raised. 422 Negative shift counts are illegal and cause a :exc:`ValueError` to be raised.
451 423
452 (2) 424 (2)
453 A left shift by *n* bits is equivalent to multiplication by ``pow(2, n)``. A 425 A left shift by *n* bits is equivalent to multiplication by ``pow(2, n)``
454 long integer is returned if the result exceeds the range of plain integers. 426 without overflow check.
455 427
456 (3) 428 (3)
457 A right shift by *n* bits is equivalent to division by ``pow(2, n)``. 429 A right shift by *n* bits is equivalent to division by ``pow(2, n)`` without
430 overflow check.
458 431
459 432
460 Additional Methods on Integer Types 433 Additional Methods on Integer Types
461 ----------------------------------- 434 -----------------------------------
462 435
463 .. method:: int.bit_length() 436 .. method:: int.bit_length()
464 .. method:: long.bit_length()
465 437
466 Return the number of bits necessary to represent an integer in binary, 438 Return the number of bits necessary to represent an integer in binary,
467 excluding the sign and leading zeros:: 439 excluding the sign and leading zeros::
468 440
469 >>> n = -37 441 >>> n = -37
470 >>> bin(n) 442 >>> bin(n)
471 '-0b100101' 443 '-0b100101'
472 >>> n.bit_length() 444 >>> n.bit_length()
473 6 445 6
474 446
475 More precisely, if ``x`` is nonzero, then ``x.bit_length()`` is the 447 More precisely, if ``x`` is nonzero, then ``x.bit_length()`` is the
476 unique positive integer ``k`` such that ``2**(k-1) <= abs(x) < 2**k``. 448 unique positive integer ``k`` such that ``2**(k-1) <= abs(x) < 2**k``.
477 Equivalently, when ``abs(x)`` is small enough to have a correctly 449 Equivalently, when ``abs(x)`` is small enough to have a correctly
478 rounded logarithm, then ``k = 1 + int(log(abs(x), 2))``. 450 rounded logarithm, then ``k = 1 + int(log(abs(x), 2))``.
479 If ``x`` is zero, then ``x.bit_length()`` returns ``0``. 451 If ``x`` is zero, then ``x.bit_length()`` returns ``0``.
480 452
481 Equivalent to:: 453 Equivalent to::
482 454
483 def bit_length(self): 455 def bit_length(self):
484 s = bin(self) # binary representation: bin(-37) --> '-0b10010 1' 456 s = bin(self) # binary representation: bin(-37) --> '-0b10010 1'
485 s = s.lstrip('-0b') # remove leading zeros and minus sign 457 s = s.lstrip('-0b') # remove leading zeros and minus sign
486 return len(s) # len('100101') --> 6 458 return len(s) # len('100101') --> 6
487 459
488 .. versionadded:: 2.7 460 .. versionadded:: 3.1
461
462 .. method:: int.to_bytes(length, byteorder, \*, signed=False)
463
464 Return an array of bytes representing an integer.
465
466 >>> (1024).to_bytes(2, byteorder='big')
467 b'\x04\x00'
468 >>> (1024).to_bytes(10, byteorder='big')
469 b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00'
470 >>> (-1024).to_bytes(10, byteorder='big', signed=True)
471 b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00'
472 >>> x = 1000
473 >>> x.to_bytes((x.bit_length() // 8) + 1, byteorder='little')
474 b'\xe8\x03'
475
476 The integer is represented using *length* bytes. An :exc:`OverflowError`
477 is raised if the integer is not representable with the given number of
478 bytes.
479
480 The *byteorder* argument determines the byte order used to represent the
481 integer. If *byteorder* is ``"big"``, the most significant byte is at the
482 beginning of the byte array. If *byteorder* is ``"little"``, the most
483 significant byte is at the end of the byte array. To request the native
484 byte order of the host system, use :data:`sys.byteorder` as the byte order
485 value.
486
487 The *signed* argument determines whether two's complement is used to
488 represent the integer. If *signed* is ``False`` and a negative integer is
489 given, an :exc:`OverflowError` is raised. The default value for *signed*
490 is ``False``.
491
492 .. versionadded:: 3.2
493
494 .. classmethod:: int.from_bytes(bytes, byteorder, \*, signed=False)
495
496 Return the integer represented by the given array of bytes.
497
498 >>> int.from_bytes(b'\x00\x10', byteorder='big')
499 16
500 >>> int.from_bytes(b'\x00\x10', byteorder='little')
501 4096
502 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True)
503 -1024
504 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False)
505 64512
506 >>> int.from_bytes([255, 0, 0], byteorder='big')
507 16711680
508
509 The argument *bytes* must either support the buffer protocol or be an
510 iterable producing bytes. :class:`bytes` and :class:`bytearray` are
511 examples of built-in objects that support the buffer protocol.
512
513 The *byteorder* argument determines the byte order used to represent the
514 integer. If *byteorder* is ``"big"``, the most significant byte is at the
515 beginning of the byte array. If *byteorder* is ``"little"``, the most
516 significant byte is at the end of the byte array. To request the native
517 byte order of the host system, use :data:`sys.byteorder` as the byte order
518 value.
519
520 The *signed* argument indicates whether two's complement is used to
521 represent the integer.
522
523 .. versionadded:: 3.2
489 524
490 525
491 Additional Methods on Float 526 Additional Methods on Float
492 --------------------------- 527 ---------------------------
493 528
494 The float type has some additional methods. 529 The float type has some additional methods.
495 530
496 .. method:: float.as_integer_ratio() 531 .. method:: float.as_integer_ratio()
497 532
498 Return a pair of integers whose ratio is exactly equal to the 533 Return a pair of integers whose ratio is exactly equal to the
499 original float and with a positive denominator. Raises 534 original float and with a positive denominator. Raises
500 :exc:`OverflowError` on infinities and a :exc:`ValueError` on 535 :exc:`OverflowError` on infinities and a :exc:`ValueError` on
501 NaNs. 536 NaNs.
502 537
503 .. versionadded:: 2.6
504
505 .. method:: float.is_integer() 538 .. method:: float.is_integer()
506 539
507 Return ``True`` if the float instance is finite with integral 540 Return ``True`` if the float instance is finite with integral
508 value, and ``False`` otherwise:: 541 value, and ``False`` otherwise::
509 542
510 >>> (-2.0).is_integer() 543 >>> (-2.0).is_integer()
511 True 544 True
512 >>> (3.2).is_integer() 545 >>> (3.2).is_integer()
513 False 546 False
514
515 .. versionadded:: 2.6
516 547
517 Two methods support conversion to 548 Two methods support conversion to
518 and from hexadecimal strings. Since Python's floats are stored 549 and from hexadecimal strings. Since Python's floats are stored
519 internally as binary numbers, converting a float to or from a 550 internally as binary numbers, converting a float to or from a
520 *decimal* string usually involves a small rounding error. In 551 *decimal* string usually involves a small rounding error. In
521 contrast, hexadecimal strings allow exact representation and 552 contrast, hexadecimal strings allow exact representation and
522 specification of floating-point numbers. This can be useful when 553 specification of floating-point numbers. This can be useful when
523 debugging, and in numerical work. 554 debugging, and in numerical work.
524 555
525 556
526 .. method:: float.hex() 557 .. method:: float.hex()
527 558
528 Return a representation of a floating-point number as a hexadecimal 559 Return a representation of a floating-point number as a hexadecimal
529 string. For finite floating-point numbers, this representation 560 string. For finite floating-point numbers, this representation
530 will always include a leading ``0x`` and a trailing ``p`` and 561 will always include a leading ``0x`` and a trailing ``p`` and
531 exponent. 562 exponent.
532 563
533 .. versionadded:: 2.6 564
534 565 .. classmethod:: float.fromhex(s)
535
536 .. method:: float.fromhex(s)
537 566
538 Class method to return the float represented by a hexadecimal 567 Class method to return the float represented by a hexadecimal
539 string *s*. The string *s* may have leading and trailing 568 string *s*. The string *s* may have leading and trailing
540 whitespace. 569 whitespace.
541
542 .. versionadded:: 2.6
543 570
544 571
545 Note that :meth:`float.hex` is an instance method, while 572 Note that :meth:`float.hex` is an instance method, while
546 :meth:`float.fromhex` is a class method. 573 :meth:`float.fromhex` is a class method.
547 574
548 A hexadecimal string takes the form:: 575 A hexadecimal string takes the form::
549 576
550 [sign] ['0x'] integer ['.' fraction] ['p' exponent] 577 [sign] ['0x'] integer ['.' fraction] ['p' exponent]
551 578
552 where the optional ``sign`` may by either ``+`` or ``-``, ``integer`` 579 where the optional ``sign`` may by either ``+`` or ``-``, ``integer``
(...skipping 19 matching lines...) Expand all
572 3740.0 599 3740.0
573 600
574 601
575 Applying the reverse conversion to ``3740.0`` gives a different 602 Applying the reverse conversion to ``3740.0`` gives a different
576 hexadecimal string representing the same number:: 603 hexadecimal string representing the same number::
577 604
578 >>> float.hex(3740.0) 605 >>> float.hex(3740.0)
579 '0x1.d380000000000p+11' 606 '0x1.d380000000000p+11'
580 607
581 608
609 .. _numeric-hash:
610
611 Hashing of numeric types
612 ------------------------
613
614 For numbers ``x`` and ``y``, possibly of different types, it's a requirement
615 that ``hash(x) == hash(y)`` whenever ``x == y`` (see the :meth:`__hash__`
616 method documentation for more details). For ease of implementation and
617 efficiency across a variety of numeric types (including :class:`int`,
618 :class:`float`, :class:`decimal.Decimal` and :class:`fractions.Fraction`)
619 Python's hash for numeric types is based on a single mathematical function
620 that's defined for any rational number, and hence applies to all instances of
621 :class:`int` and :class:`fraction.Fraction`, and all finite instances of
622 :class:`float` and :class:`decimal.Decimal`. Essentially, this function is
623 given by reduction modulo ``P`` for a fixed prime ``P``. The value of ``P`` is
624 made available to Python as the :attr:`modulus` attribute of
625 :data:`sys.hash_info`.
626
627 .. impl-detail::
628
629 Currently, the prime used is ``P = 2**31 - 1`` on machines with 32-bit C
630 longs and ``P = 2**61 - 1`` on machines with 64-bit C longs.
631
632 Here are the rules in detail:
633
634 - If ``x = m / n`` is a nonnegative rational number and ``n`` is not divisible
635 by ``P``, define ``hash(x)`` as ``m * invmod(n, P) % P``, where ``invmod(n,
636 P)`` gives the inverse of ``n`` modulo ``P``.
637
638 - If ``x = m / n`` is a nonnegative rational number and ``n`` is
639 divisible by ``P`` (but ``m`` is not) then ``n`` has no inverse
640 modulo ``P`` and the rule above doesn't apply; in this case define
641 ``hash(x)`` to be the constant value ``sys.hash_info.inf``.
642
643 - If ``x = m / n`` is a negative rational number define ``hash(x)``
644 as ``-hash(-x)``. If the resulting hash is ``-1``, replace it with
645 ``-2``.
646
647 - The particular values ``sys.hash_info.inf``, ``-sys.hash_info.inf``
648 and ``sys.hash_info.nan`` are used as hash values for positive
649 infinity, negative infinity, or nans (respectively). (All hashable
650 nans have the same hash value.)
651
652 - For a :class:`complex` number ``z``, the hash values of the real
653 and imaginary parts are combined by computing ``hash(z.real) +
654 sys.hash_info.imag * hash(z.imag)``, reduced modulo
655 ``2**sys.hash_info.width`` so that it lies in
656 ``range(-2**(sys.hash_info.width - 1), 2**(sys.hash_info.width -
657 1))``. Again, if the result is ``-1``, it's replaced with ``-2``.
658
659
660 To clarify the above rules, here's some example Python code,
661 equivalent to the builtin hash, for computing the hash of a rational
662 number, :class:`float`, or :class:`complex`::
663
664
665 import sys, math
666
667 def hash_fraction(m, n):
668 """Compute the hash of a rational number m / n.
669
670 Assumes m and n are integers, with n positive.
671 Equivalent to hash(fractions.Fraction(m, n)).
672
673 """
674 P = sys.hash_info.modulus
675 # Remove common factors of P. (Unnecessary if m and n already coprime.)
676 while m % P == n % P == 0:
677 m, n = m // P, n // P
678
679 if n % P == 0:
680 hash_ = sys.hash_info.inf
681 else:
682 # Fermat's Little Theorem: pow(n, P-1, P) is 1, so
683 # pow(n, P-2, P) gives the inverse of n modulo P.
684 hash_ = (abs(m) % P) * pow(n, P - 2, P) % P
685 if m < 0:
686 hash_ = -hash_
687 if hash_ == -1:
688 hash_ = -2
689 return hash_
690
691 def hash_float(x):
692 """Compute the hash of a float x."""
693
694 if math.isnan(x):
695 return sys.hash_info.nan
696 elif math.isinf(x):
697 return sys.hash_info.inf if x > 0 else -sys.hash_info.inf
698 else:
699 return hash_fraction(*x.as_integer_ratio())
700
701 def hash_complex(z):
702 """Compute the hash of a complex number z."""
703
704 hash_ = hash_float(z.real) + sys.hash_info.imag * hash_float(z.imag)
705 # do a signed reduction modulo 2**sys.hash_info.width
706 M = 2**(sys.hash_info.width - 1)
707 hash_ = (hash_ & (M - 1)) - (hash & M)
708 if hash_ == -1:
709 hash_ == -2
710 return hash_
711
582 .. _typeiter: 712 .. _typeiter:
583 713
584 Iterator Types 714 Iterator Types
585 ============== 715 ==============
586
587 .. versionadded:: 2.2
588 716
589 .. index:: 717 .. index::
590 single: iterator protocol 718 single: iterator protocol
591 single: protocol; iterator 719 single: protocol; iterator
592 single: sequence; iteration 720 single: sequence; iteration
593 single: container; iteration over 721 single: container; iteration over
594 722
595 Python supports a concept of iteration over containers. This is implemented 723 Python supports a concept of iteration over containers. This is implemented
596 using two distinct methods; these are used to allow user-defined classes to 724 using two distinct methods; these are used to allow user-defined classes to
597 support iteration. Sequences, described below in more detail, always support 725 support iteration. Sequences, described below in more detail, always support
(...skipping 20 matching lines...) Expand all
618 746
619 747
620 .. method:: iterator.__iter__() 748 .. method:: iterator.__iter__()
621 749
622 Return the iterator object itself. This is required to allow both containers 750 Return the iterator object itself. This is required to allow both containers
623 and iterators to be used with the :keyword:`for` and :keyword:`in` statements . 751 and iterators to be used with the :keyword:`for` and :keyword:`in` statements .
624 This method corresponds to the :attr:`tp_iter` slot of the type structure for 752 This method corresponds to the :attr:`tp_iter` slot of the type structure for
625 Python objects in the Python/C API. 753 Python objects in the Python/C API.
626 754
627 755
628 .. method:: iterator.next() 756 .. method:: iterator.__next__()
629 757
630 Return the next item from the container. If there are no further items, rais e 758 Return the next item from the container. If there are no further items, rais e
631 the :exc:`StopIteration` exception. This method corresponds to the 759 the :exc:`StopIteration` exception. This method corresponds to the
632 :attr:`tp_iternext` slot of the type structure for Python objects in the 760 :attr:`tp_iternext` slot of the type structure for Python objects in the
633 Python/C API. 761 Python/C API.
634 762
635 Python defines several iterator objects to support iteration over general and 763 Python defines several iterator objects to support iteration over general and
636 specific sequence types, dictionaries, and other more specialized forms. The 764 specific sequence types, dictionaries, and other more specialized forms. The
637 specific types are not important beyond their implementation of the iterator 765 specific types are not important beyond their implementation of the iterator
638 protocol. 766 protocol.
639 767
640 The intention of the protocol is that once an iterator's :meth:`next` method 768 Once an iterator's :meth:`__next__` method raises :exc:`StopIteration`, it must
641 raises :exc:`StopIteration`, it will continue to do so on subsequent calls. 769 continue to do so on subsequent calls. Implementations that do not obey this
642 Implementations that do not obey this property are deemed broken. (This 770 property are deemed broken.
643 constraint was added in Python 2.3; in Python 2.2, various iterators are broken
644 according to this rule.)
645 771
646 772
647 .. _generator-types: 773 .. _generator-types:
648 774
649 Generator Types 775 Generator Types
650 --------------- 776 ---------------
651 777
652 Python's :term:`generator`\s provide a convenient way to implement the iterator 778 Python's :term:`generator`\s provide a convenient way to implement the iterator
653 protocol. If a container object's :meth:`__iter__` method is implemented as a 779 protocol. If a container object's :meth:`__iter__` method is implemented as a
654 generator, it will automatically return an iterator object (technically, a 780 generator, it will automatically return an iterator object (technically, a
655 generator object) supplying the :meth:`__iter__` and :meth:`next` methods. More 781 generator object) supplying the :meth:`__iter__` and :meth:`__next__` methods.
656 information about generators can be found in :ref:`the documentation for the 782 More information about generators can be found in :ref:`the documentation for
657 yield expression <yieldexpr>`. 783 the yield expression <yieldexpr>`.
658 784
659 785
660 .. _typesseq: 786 .. _typesseq:
661 787
662 Sequence Types --- :class:`str`, :class:`unicode`, :class:`list`, :class:`tuple` , :class:`bytearray`, :class:`buffer`, :class:`xrange` 788 Sequence Types --- :class:`str`, :class:`bytes`, :class:`bytearray`, :class:`lis t`, :class:`tuple`, :class:`range`
663 ================================================================================ ====================================================== 789 ================================================================================ ==================================
664 790
665 There are seven sequence types: strings, Unicode strings, lists, tuples, 791 There are six sequence types: strings, byte sequences (:class:`bytes` objects),
666 bytearrays, buffers, and xrange objects. 792 byte arrays (:class:`bytearray` objects), lists, tuples, and range objects. For
667 793 other containers see the built in :class:`dict` and :class:`set` classes, and
668 For other containers see the built in :class:`dict` and :class:`set` classes, 794 the :mod:`collections` module.
669 and the :mod:`collections` module.
670 795
671 796
672 .. index:: 797 .. index::
673 object: sequence 798 object: sequence
674 object: string 799 object: string
675 object: Unicode 800 object: bytes
801 object: bytearray
676 object: tuple 802 object: tuple
677 object: list 803 object: list
678 object: bytearray 804 object: range
679 object: buffer 805
680 object: xrange 806 Strings contain Unicode characters. Their literals are written in single or
681 807 double quotes: ``'xyzzy'``, ``"frobozz"``. See :ref:`strings` for more about
682 String literals are written in single or double quotes: ``'xyzzy'``, 808 string literals. In addition to the functionality described here, there are
683 ``"frobozz"``. See :ref:`strings` for more about string literals. 809 also string-specific methods described in the :ref:`string-methods` section.
684 Unicode strings are much like strings, but are specified in the syntax 810
685 using a preceding ``'u'`` character: ``u'abc'``, ``u"def"``. In addition 811 Bytes and bytearray objects contain single bytes -- the former is immutable
686 to the functionality described here, there are also string-specific 812 while the latter is a mutable sequence. Bytes objects can be constructed the
687 methods described in the :ref:`string-methods` section. Lists are 813 constructor, :func:`bytes`, and from literals; use a ``b`` prefix with normal
688 constructed with square brackets, separating items with commas: ``[a, b, c]``. 814 string syntax: ``b'xyzzy'``. To construct byte arrays, use the
689 Tuples are constructed by the comma operator (not within square 815 :func:`bytearray` function.
690 brackets), with or without enclosing parentheses, but an empty tuple 816
691 must have the enclosing parentheses, such as ``a, b, c`` or ``()``. A 817 While string objects are sequences of characters (represented by strings of
692 single item tuple must have a trailing comma, such as ``(d,)``. 818 length 1), bytes and bytearray objects are sequences of *integers* (between 0
693 819 and 255), representing the ASCII value of single bytes. That means that for
694 Bytearray objects are created with the built-in function :func:`bytearray`. 820 a bytes or bytearray object *b*, ``b[0]`` will be an integer, while
695 821 ``b[0:1]`` will be a bytes or bytearray object of length 1. The
696 Buffer objects are not directly supported by Python syntax, but can be created 822 representation of bytes objects uses the literal format (``b'...'``) since it
697 by calling the built-in function :func:`buffer`. They don't support 823 is generally more useful than e.g. ``bytes([50, 19, 100])``. You can always
698 concatenation or repetition. 824 convert a bytes object into a list of integers using ``list(b)``.
699 825
700 Objects of type xrange are similar to buffers in that there is no specific synta x to 826 Also, while in previous Python versions, byte strings and Unicode strings
701 create them, but they are created using the :func:`xrange` function. They don't 827 could be exchanged for each other rather freely (barring encoding issues),
702 support slicing, concatenation or repetition, and using ``in``, ``not in``, 828 strings and bytes are now completely separate concepts. There's no implicit
703 :func:`min` or :func:`max` on them is inefficient. 829 en-/decoding if you pass an object of the wrong type. A string always
830 compares unequal to a bytes or bytearray object.
831
832 Lists are constructed with square brackets, separating items with commas: ``[a,
833 b, c]``. Tuples are constructed by the comma operator (not within square
834 brackets), with or without enclosing parentheses, but an empty tuple must have
835 the enclosing parentheses, such as ``a, b, c`` or ``()``. A single item tuple
836 must have a trailing comma, such as ``(d,)``.
837
838 Objects of type range are created using the :func:`range` function. They don't
839 support concatenation or repetition, and using :func:`min` or :func:`max` on
840 them is inefficient.
704 841
705 Most sequence types support the following operations. The ``in`` and ``not in`` 842 Most sequence types support the following operations. The ``in`` and ``not in``
706 operations have the same priorities as the comparison operations. The ``+`` and 843 operations have the same priorities as the comparison operations. The ``+`` and
707 ``*`` operations have the same priority as the corresponding numeric operations. 844 ``*`` operations have the same priority as the corresponding numeric operations.
708 [#]_ Additional methods are provided for :ref:`typesseq-mutable`. 845 [#]_ Additional methods are provided for :ref:`typesseq-mutable`.
709 846
710 This table lists the sequence operations sorted in ascending priority 847 This table lists the sequence operations sorted in ascending priority
711 (operations in the same box have the same priority). In the table, *s* and *t* 848 (operations in the same box have the same priority). In the table, *s* and *t*
712 are sequences of the same type; *n*, *i* and *j* are integers: 849 are sequences of the same type; *n*, *i*, *j* and *k* are integers.
713 850
714 +------------------+--------------------------------+----------+ 851 +------------------+--------------------------------+----------+
715 | Operation | Result | Notes | 852 | Operation | Result | Notes |
716 +==================+================================+==========+ 853 +==================+================================+==========+
717 | ``x in s`` | ``True`` if an item of *s* is | \(1) | 854 | ``x in s`` | ``True`` if an item of *s* is | \(1) |
718 | | equal to *x*, else ``False`` | | 855 | | equal to *x*, else ``False`` | |
719 +------------------+--------------------------------+----------+ 856 +------------------+--------------------------------+----------+
720 | ``x not in s`` | ``False`` if an item of *s* is | \(1) | 857 | ``x not in s`` | ``False`` if an item of *s* is | \(1) |
721 | | equal to *x*, else ``True`` | | 858 | | equal to *x*, else ``True`` | |
722 +------------------+--------------------------------+----------+ 859 +------------------+--------------------------------+----------+
(...skipping 16 matching lines...) Expand all
739 +------------------+--------------------------------+----------+ 876 +------------------+--------------------------------+----------+
740 | ``max(s)`` | largest item of *s* | | 877 | ``max(s)`` | largest item of *s* | |
741 +------------------+--------------------------------+----------+ 878 +------------------+--------------------------------+----------+
742 | ``s.index(i)`` | index of the first occurence | | 879 | ``s.index(i)`` | index of the first occurence | |
743 | | of *i* in *s* | | 880 | | of *i* in *s* | |
744 +------------------+--------------------------------+----------+ 881 +------------------+--------------------------------+----------+
745 | ``s.count(i)`` | total number of occurences of | | 882 | ``s.count(i)`` | total number of occurences of | |
746 | | *i* in *s* | | 883 | | *i* in *s* | |
747 +------------------+--------------------------------+----------+ 884 +------------------+--------------------------------+----------+
748 885
749 Sequence types also support comparisons. In particular, tuples and lists 886 Sequence types also support comparisons. In particular, tuples and lists are
750 are compared lexicographically by comparing corresponding 887 compared lexicographically by comparing corresponding elements. This means that
751 elements. This means that to compare equal, every element must compare 888 to compare equal, every element must compare equal and the two sequences must be
752 equal and the two sequences must be of the same type and have the same 889 of the same type and have the same length. (For full details see
753 length. (For full details see :ref:`comparisons` in the language 890 :ref:`comparisons` in the language reference.)
754 reference.)
755 891
756 .. index:: 892 .. index::
757 triple: operations on; sequence; types 893 triple: operations on; sequence; types
758 builtin: len 894 builtin: len
759 builtin: min 895 builtin: min
760 builtin: max 896 builtin: max
761 pair: concatenation; operation 897 pair: concatenation; operation
762 pair: repetition; operation 898 pair: repetition; operation
763 pair: subscript; operation 899 pair: subscript; operation
764 pair: slice; operation 900 pair: slice; operation
765 pair: extended slice; operation
766 operator: in 901 operator: in
767 operator: not in 902 operator: not in
768 903
769 Notes: 904 Notes:
770 905
771 (1) 906 (1)
772 When *s* is a string or Unicode string object the ``in`` and ``not in`` 907 When *s* is a string object, the ``in`` and ``not in`` operations act like a
773 operations act like a substring test. In Python versions before 2.3, *x* had to 908 substring test.
774 be a string of length 1. In Python 2.3 and beyond, *x* may be a string of any
775 length.
776 909
777 (2) 910 (2)
778 Values of *n* less than ``0`` are treated as ``0`` (which yields an empty 911 Values of *n* less than ``0`` are treated as ``0`` (which yields an empty
779 sequence of the same type as *s*). Note also that the copies are shallow; 912 sequence of the same type as *s*). Note also that the copies are shallow;
780 nested structures are not copied. This often haunts new Python programmers; 913 nested structures are not copied. This often haunts new Python programmers;
781 consider: 914 consider:
782 915
783 >>> lists = [[]] * 3 916 >>> lists = [[]] * 3
784 >>> lists 917 >>> lists
785 [[], [], []] 918 [[], [], []]
786 >>> lists[0].append(3) 919 >>> lists[0].append(3)
787 >>> lists 920 >>> lists
788 [[3], [3], [3]] 921 [[3], [3], [3]]
789 922
790 What has happened is that ``[[]]`` is a one-element list containing an empty 923 What has happened is that ``[[]]`` is a one-element list containing an empty
791 list, so all three elements of ``[[]] * 3`` are (pointers to) this single emp ty 924 list, so all three elements of ``[[]] * 3`` are (pointers to) this single emp ty
792 list. Modifying any of the elements of ``lists`` modifies this single list. 925 list. Modifying any of the elements of ``lists`` modifies this single list.
793 You can create a list of different lists this way: 926 You can create a list of different lists this way:
794 927
795 >>> lists = [[] for i in range(3)] 928 >>> lists = [[] for i in range(3)]
796 >>> lists[0].append(3) 929 >>> lists[0].append(3)
797 >>> lists[1].append(5) 930 >>> lists[1].append(5)
798 >>> lists[2].append(7) 931 >>> lists[2].append(7)
799 >>> lists 932 >>> lists
800 [[3], [5], [7]] 933 [[3], [5], [7]]
801 934
802 (3) 935 (3)
803 If *i* or *j* is negative, the index is relative to the end of the string: 936 If *i* or *j* is negative, the index is relative to the end of the string:
804 ``len(s) + i`` or ``len(s) + j`` is substituted. But note that ``-0`` is sti ll 937 ``len(s) + i`` or ``len(s) + j`` is substituted. But note that ``-0`` is
805 ``0``. 938 still ``0``.
806 939
807 (4) 940 (4)
808 The slice of *s* from *i* to *j* is defined as the sequence of items with ind ex 941 The slice of *s* from *i* to *j* is defined as the sequence of items with ind ex
809 *k* such that ``i <= k < j``. If *i* or *j* is greater than ``len(s)``, use 942 *k* such that ``i <= k < j``. If *i* or *j* is greater than ``len(s)``, use
810 ``len(s)``. If *i* is omitted or ``None``, use ``0``. If *j* is omitted or 943 ``len(s)``. If *i* is omitted or ``None``, use ``0``. If *j* is omitted or
811 ``None``, use ``len(s)``. If *i* is greater than or equal to *j*, the slice is 944 ``None``, use ``len(s)``. If *i* is greater than or equal to *j*, the slice is
812 empty. 945 empty.
813 946
814 (5) 947 (5)
815 The slice of *s* from *i* to *j* with step *k* is defined as the sequence of 948 The slice of *s* from *i* to *j* with step *k* is defined as the sequence of
816 items with index ``x = i + n*k`` such that ``0 <= n < (j-i)/k``. In other w ords, 949 items with index ``x = i + n*k`` such that ``0 <= n < (j-i)/k``. In other w ords,
817 the indices are ``i``, ``i+k``, ``i+2*k``, ``i+3*k`` and so on, stopping when 950 the indices are ``i``, ``i+k``, ``i+2*k``, ``i+3*k`` and so on, stopping when
818 *j* is reached (but never including *j*). If *i* or *j* is greater than 951 *j* is reached (but never including *j*). If *i* or *j* is greater than
819 ``len(s)``, use ``len(s)``. If *i* or *j* are omitted or ``None``, they beco me 952 ``len(s)``, use ``len(s)``. If *i* or *j* are omitted or ``None``, they beco me
820 "end" values (which end depends on the sign of *k*). Note, *k* cannot be zer o. 953 "end" values (which end depends on the sign of *k*). Note, *k* cannot be zer o.
821 If *k* is ``None``, it is treated like ``1``. 954 If *k* is ``None``, it is treated like ``1``.
822 955
823 (6) 956 (6)
824 .. impl-detail:: 957 .. impl-detail::
825 958
826 If *s* and *t* are both strings, some Python implementations such as 959 If *s* and *t* are both strings, some Python implementations such as
827 CPython can usually perform an in-place optimization for assignments of 960 CPython can usually perform an in-place optimization for assignments of
828 the form ``s = s + t`` or ``s += t``. When applicable, this optimization 961 the form ``s = s + t`` or ``s += t``. When applicable, this optimization
829 makes quadratic run-time much less likely. This optimization is both 962 makes quadratic run-time much less likely. This optimization is both
830 version and implementation dependent. For performance sensitive code, it 963 version and implementation dependent. For performance sensitive code, it
831 is preferable to use the :meth:`str.join` method which assures consistent 964 is preferable to use the :meth:`str.join` method which assures consistent
832 linear concatenation performance across versions and implementations. 965 linear concatenation performance across versions and implementations.
833 966
834 .. versionchanged:: 2.4
835 Formerly, string concatenation never occurred in-place.
836
837 967
838 .. _string-methods: 968 .. _string-methods:
839 969
840 String Methods 970 String Methods
841 -------------- 971 --------------
842 972
843 .. index:: pair: string; methods 973 .. index:: pair: string; methods
844 974
845 Below are listed the string methods which both 8-bit strings and 975 String objects support the methods listed below.
846 Unicode objects support. Some of them are also available on :class:`bytearray` 976
847 objects. 977 In addition, Python's strings support the sequence type methods described in the
848 978 :ref:`typesseq` section. To output formatted strings, see the
849 In addition, Python's strings support the sequence type methods 979 :ref:`string-formatting` section. Also, see the :mod:`re` module for string
850 described in the :ref:`typesseq` section. To output formatted strings 980 functions based on regular expressions.
851 use template strings or the ``%`` operator described in the
852 :ref:`string-formatting` section. Also, see the :mod:`re` module for
853 string functions based on regular expressions.
854 981
855 .. method:: str.capitalize() 982 .. method:: str.capitalize()
856 983
857 Return a copy of the string with its first character capitalized and the 984 Return a copy of the string with its first character capitalized and the
858 rest lowercased. 985 rest lowercased.
859 986
860 For 8-bit strings, this method is locale-dependent.
861
862 987
863 .. method:: str.center(width[, fillchar]) 988 .. method:: str.center(width[, fillchar])
864 989
865 Return centered in a string of length *width*. Padding is done using the 990 Return centered in a string of length *width*. Padding is done using the
866 specified *fillchar* (default is a space). 991 specified *fillchar* (default is a space).
867
868 .. versionchanged:: 2.4
869 Support for the *fillchar* argument.
870 992
871 993
872 .. method:: str.count(sub[, start[, end]]) 994 .. method:: str.count(sub[, start[, end]])
873 995
874 Return the number of non-overlapping occurrences of substring *sub* in the 996 Return the number of non-overlapping occurrences of substring *sub* in the
875 range [*start*, *end*]. Optional arguments *start* and *end* are 997 range [*start*, *end*]. Optional arguments *start* and *end* are
876 interpreted as in slice notation. 998 interpreted as in slice notation.
877 999
878 1000
879 .. method:: str.decode([encoding[, errors]]) 1001 .. method:: str.encode(encoding="utf-8", errors="strict")
880 1002
881 Decodes the string using the codec registered for *encoding*. *encoding* 1003 Return an encoded version of the string as a bytes object. Default encoding
882 defaults to the default string encoding. *errors* may be given to set a 1004 is ``'utf-8'``. *errors* may be given to set a different error handling schem e.
883 different error handling scheme. The default is ``'strict'``, meaning that 1005 The default for *errors* is ``'strict'``, meaning that encoding errors raise
884 encoding errors raise :exc:`UnicodeError`. Other possible values are 1006 a :exc:`UnicodeError`. Other possible
885 ``'ignore'``, ``'replace'`` and any other name registered via 1007 values are ``'ignore'``, ``'replace'``, ``'xmlcharrefreplace'``,
886 :func:`codecs.register_error`, see section :ref:`codec-base-classes`. 1008 ``'backslashreplace'`` and any other name registered via
887 1009 :func:`codecs.register_error`, see section :ref:`codec-base-classes`. For a
888 .. versionadded:: 2.2 1010 list of possible encodings, see section :ref:`standard-encodings`.
889 1011
890 .. versionchanged:: 2.3 1012 .. versionchanged:: 3.1
891 Support for other error handling schemes added.
892
893 .. versionchanged:: 2.7
894 Support for keyword arguments added. 1013 Support for keyword arguments added.
895 1014
896 .. method:: str.encode([encoding[,errors]])
897
898 Return an encoded version of the string. Default encoding is the current
899 default string encoding. *errors* may be given to set a different error
900 handling scheme. The default for *errors* is ``'strict'``, meaning that
901 encoding errors raise a :exc:`UnicodeError`. Other possible values are
902 ``'ignore'``, ``'replace'``, ``'xmlcharrefreplace'``, ``'backslashreplace'`` and
903 any other name registered via :func:`codecs.register_error`, see section
904 :ref:`codec-base-classes`. For a list of possible encodings, see section
905 :ref:`standard-encodings`.
906
907 .. versionadded:: 2.0
908
909 .. versionchanged:: 2.3
910 Support for ``'xmlcharrefreplace'`` and ``'backslashreplace'`` and other e rror
911 handling schemes added.
912
913 .. versionchanged:: 2.7
914 Support for keyword arguments added.
915 1015
916 .. method:: str.endswith(suffix[, start[, end]]) 1016 .. method:: str.endswith(suffix[, start[, end]])
917 1017
918 Return ``True`` if the string ends with the specified *suffix*, otherwise ret urn 1018 Return ``True`` if the string ends with the specified *suffix*, otherwise ret urn
919 ``False``. *suffix* can also be a tuple of suffixes to look for. With optio nal 1019 ``False``. *suffix* can also be a tuple of suffixes to look for. With optio nal
920 *start*, test beginning at that position. With optional *end*, stop comparin g 1020 *start*, test beginning at that position. With optional *end*, stop comparin g
921 at that position. 1021 at that position.
922
923 .. versionchanged:: 2.5
924 Accept tuples as *suffix*.
925 1022
926 1023
927 .. method:: str.expandtabs([tabsize]) 1024 .. method:: str.expandtabs([tabsize])
928 1025
929 Return a copy of the string where all tab characters are replaced by one or 1026 Return a copy of the string where all tab characters are replaced by one or
930 more spaces, depending on the current column and the given tab size. The 1027 more spaces, depending on the current column and the given tab size. The
931 column number is reset to zero after each newline occurring in the string. 1028 column number is reset to zero after each newline occurring in the string.
932 If *tabsize* is not given, a tab size of ``8`` characters is assumed. This 1029 If *tabsize* is not given, a tab size of ``8`` characters is assumed. This
933 doesn't understand other non-printing characters or escape sequences. 1030 doesn't understand other non-printing characters or escape sequences.
934 1031
(...skipping 14 matching lines...) Expand all
949 positional argument, or the name of a keyword argument. Returns a copy of 1046 positional argument, or the name of a keyword argument. Returns a copy of
950 the string where each replacement field is replaced with the string value of 1047 the string where each replacement field is replaced with the string value of
951 the corresponding argument. 1048 the corresponding argument.
952 1049
953 >>> "The sum of 1 + 2 is {0}".format(1+2) 1050 >>> "The sum of 1 + 2 is {0}".format(1+2)
954 'The sum of 1 + 2 is 3' 1051 'The sum of 1 + 2 is 3'
955 1052
956 See :ref:`formatstrings` for a description of the various formatting options 1053 See :ref:`formatstrings` for a description of the various formatting options
957 that can be specified in format strings. 1054 that can be specified in format strings.
958 1055
959 This method of string formatting is the new standard in Python 3.0, and 1056
960 should be preferred to the ``%`` formatting described in 1057 .. method:: str.format_map(mapping)
961 :ref:`string-formatting` in new code. 1058
962 1059 Similar to ``str.format(**mapping)``, except that ``mapping`` is
963 .. versionadded:: 2.6 1060 used directly and not copied to a :class:`dict` . This is useful
1061 if for example ``mapping`` is a dict subclass:
1062
1063 >>> class Default(dict):
1064 ... def __missing__(self, key):
1065 ... return key
1066 ...
1067 >>> '{name} was born in {country}'.format_map(Default(name='Guido'))
1068 'Guido was born in country'
1069
1070 .. versionadded:: 3.2
964 1071
965 1072
966 .. method:: str.index(sub[, start[, end]]) 1073 .. method:: str.index(sub[, start[, end]])
967 1074
968 Like :meth:`find`, but raise :exc:`ValueError` when the substring is not foun d. 1075 Like :meth:`find`, but raise :exc:`ValueError` when the substring is not foun d.
969 1076
970 1077
971 .. method:: str.isalnum() 1078 .. method:: str.isalnum()
972 1079
973 Return true if all characters in the string are alphanumeric and there is at 1080 Return true if all characters in the string are alphanumeric and there is at
974 least one character, false otherwise. 1081 least one character, false otherwise. A character ``c`` is alphanumeric if o ne
975 1082 of the following returns ``True``: ``c.isalpha()``, ``c.isdecimal()``,
976 For 8-bit strings, this method is locale-dependent. 1083 ``c.isdigit()``, or ``c.isnumeric()``.
977 1084
978 1085
979 .. method:: str.isalpha() 1086 .. method:: str.isalpha()
980 1087
981 Return true if all characters in the string are alphabetic and there is at le ast 1088 Return true if all characters in the string are alphabetic and there is at le ast
982 one character, false otherwise. 1089 one character, false otherwise. Alphabetic characters are those characters d efined
983 1090 in the Unicode character database as "Letter", i.e., those with general categ ory
984 For 8-bit strings, this method is locale-dependent. 1091 property being one of "Lm", "Lt", "Lu", "Ll", or "Lo". Note that this is dif ferent
1092 from the "Alphabetic" property defined in the Unicode Standard.
1093
1094
1095 .. method:: str.isdecimal()
1096
1097 Return true if all characters in the string are decimal
1098 characters and there is at least one character, false
1099 otherwise. Decimal characters are those from general category "Nd". This cate gory
1100 includes digit characters, and all characters
1101 that that can be used to form decimal-radix numbers, e.g. U+0660,
1102 ARABIC-INDIC DIGIT ZERO.
985 1103
986 1104
987 .. method:: str.isdigit() 1105 .. method:: str.isdigit()
988 1106
989 Return true if all characters in the string are digits and there is at least one 1107 Return true if all characters in the string are digits and there is at least one
990 character, false otherwise. 1108 character, false otherwise. Digits include decimal characters and digits tha t need
991 1109 special handling, such as the compatibility superscript digits. Formally, a digit
992 For 8-bit strings, this method is locale-dependent. 1110 is a character that has the property value Numeric_Type=Digit or Numeric_Type =Decimal.
1111
1112
1113 .. method:: str.isidentifier()
1114
1115 Return true if the string is a valid identifier according to the language
1116 definition, section :ref:`identifiers`.
993 1117
994 1118
995 .. method:: str.islower() 1119 .. method:: str.islower()
996 1120
997 Return true if all cased characters in the string are lowercase and there is at 1121 Return true if all cased characters in the string are lowercase and there is at
998 least one cased character, false otherwise. 1122 least one cased character, false otherwise. Cased characters are those with
999 1123 general category property being one of "Lu", "Ll", or "Lt" and lowercase char acters
1000 For 8-bit strings, this method is locale-dependent. 1124 are those with general category property "Ll".
1125
1126
1127 .. method:: str.isnumeric()
1128
1129 Return true if all characters in the string are numeric
1130 characters, and there is at least one character, false
1131 otherwise. Numeric characters include digit characters, and all characters
1132 that have the Unicode numeric value property, e.g. U+2155,
1133 VULGAR FRACTION ONE FIFTH. Formally, numeric characters are those with the p roperty
1134 value Numeric_Type=Digit, Numeric_Type=Decimal or Numeric_Type=Numeric.
1135
1136
1137 .. method:: str.isprintable()
1138
1139 Return true if all characters in the string are printable or the string is
1140 empty, false otherwise. Nonprintable characters are those characters defined
1141 in the Unicode character database as "Other" or "Separator", excepting the
1142 ASCII space (0x20) which is considered printable. (Note that printable
1143 characters in this context are those which should not be escaped when
1144 :func:`repr` is invoked on a string. It has no bearing on the handling of
1145 strings written to :data:`sys.stdout` or :data:`sys.stderr`.)
1001 1146
1002 1147
1003 .. method:: str.isspace() 1148 .. method:: str.isspace()
1004 1149
1005 Return true if there are only whitespace characters in the string and there i s 1150 Return true if there are only whitespace characters in the string and there i s
1006 at least one character, false otherwise. 1151 at least one character, false otherwise. Whitespace characters are those
1007 1152 characters defined in the Unicode character database as "Other" or "Separator "
1008 For 8-bit strings, this method is locale-dependent. 1153 and those with bidirectional property being one of "WS", "B", or "S".
1009
1010 1154
1011 .. method:: str.istitle() 1155 .. method:: str.istitle()
1012 1156
1013 Return true if the string is a titlecased string and there is at least one 1157 Return true if the string is a titlecased string and there is at least one
1014 character, for example uppercase characters may only follow uncased character s 1158 character, for example uppercase characters may only follow uncased character s
1015 and lowercase characters only cased ones. Return false otherwise. 1159 and lowercase characters only cased ones. Return false otherwise.
1016 1160
1017 For 8-bit strings, this method is locale-dependent.
1018
1019 1161
1020 .. method:: str.isupper() 1162 .. method:: str.isupper()
1021 1163
1022 Return true if all cased characters in the string are uppercase and there is at 1164 Return true if all cased characters in the string are uppercase and there is at
1023 least one cased character, false otherwise. 1165 least one cased character, false otherwise. Cased characters are those with
1024 1166 general category property being one of "Lu", "Ll", or "Lt" and uppercase char acters
1025 For 8-bit strings, this method is locale-dependent. 1167 are those with general category property "Lu".
1026 1168
1027 1169
1028 .. method:: str.join(iterable) 1170 .. method:: str.join(iterable)
1029 1171
1030 Return a string which is the concatenation of the strings in the 1172 Return a string which is the concatenation of the strings in the
1031 :term:`iterable` *iterable*. The separator between elements is the string 1173 :term:`iterable` *iterable*. A :exc:`TypeError` will be raised if there are
1032 providing this method. 1174 any non-string values in *seq*, including :class:`bytes` objects. The
1175 separator between elements is the string providing this method.
1033 1176
1034 1177
1035 .. method:: str.ljust(width[, fillchar]) 1178 .. method:: str.ljust(width[, fillchar])
1036 1179
1037 Return the string left justified in a string of length *width*. Padding is do ne 1180 Return the string left justified in a string of length *width*. Padding is do ne
1038 using the specified *fillchar* (default is a space). The original string is 1181 using the specified *fillchar* (default is a space). The original string is
1039 returned if *width* is less than ``len(s)``. 1182 returned if *width* is less than ``len(s)``.
1040 1183
1041 .. versionchanged:: 2.4
1042 Support for the *fillchar* argument.
1043
1044 1184
1045 .. method:: str.lower() 1185 .. method:: str.lower()
1046 1186
1047 Return a copy of the string converted to lowercase. 1187 Return a copy of the string converted to lowercase.
1048
1049 For 8-bit strings, this method is locale-dependent.
1050 1188
1051 1189
1052 .. method:: str.lstrip([chars]) 1190 .. method:: str.lstrip([chars])
1053 1191
1054 Return a copy of the string with leading characters removed. The *chars* 1192 Return a copy of the string with leading characters removed. The *chars*
1055 argument is a string specifying the set of characters to be removed. If omit ted 1193 argument is a string specifying the set of characters to be removed. If omit ted
1056 or ``None``, the *chars* argument defaults to removing whitespace. The *char s* 1194 or ``None``, the *chars* argument defaults to removing whitespace. The *char s*
1057 argument is not a prefix; rather, all combinations of its values are stripped : 1195 argument is not a prefix; rather, all combinations of its values are stripped :
1058 1196
1059 >>> ' spacious '.lstrip() 1197 >>> ' spacious '.lstrip()
1060 'spacious ' 1198 'spacious '
1061 >>> 'www.example.com'.lstrip('cmowz.') 1199 >>> 'www.example.com'.lstrip('cmowz.')
1062 'example.com' 1200 'example.com'
1063 1201
1064 .. versionchanged:: 2.2.2 1202
1065 Support for the *chars* argument. 1203 .. staticmethod:: str.maketrans(x[, y[, z]])
1204
1205 This static method returns a translation table usable for :meth:`str.translat e`.
1206
1207 If there is only one argument, it must be a dictionary mapping Unicode
1208 ordinals (integers) or characters (strings of length 1) to Unicode ordinals,
1209 strings (of arbitrary lengths) or None. Character keys will then be
1210 converted to ordinals.
1211
1212 If there are two arguments, they must be strings of equal length, and in the
1213 resulting dictionary, each character in x will be mapped to the character at
1214 the same position in y. If there is a third argument, it must be a string,
1215 whose characters will be mapped to None in the result.
1066 1216
1067 1217
1068 .. method:: str.partition(sep) 1218 .. method:: str.partition(sep)
1069 1219
1070 Split the string at the first occurrence of *sep*, and return a 3-tuple 1220 Split the string at the first occurrence of *sep*, and return a 3-tuple
1071 containing the part before the separator, the separator itself, and the part 1221 containing the part before the separator, the separator itself, and the part
1072 after the separator. If the separator is not found, return a 3-tuple contain ing 1222 after the separator. If the separator is not found, return a 3-tuple contain ing
1073 the string itself, followed by two empty strings. 1223 the string itself, followed by two empty strings.
1074 1224
1075 .. versionadded:: 2.5
1076
1077 1225
1078 .. method:: str.replace(old, new[, count]) 1226 .. method:: str.replace(old, new[, count])
1079 1227
1080 Return a copy of the string with all occurrences of substring *old* replaced by 1228 Return a copy of the string with all occurrences of substring *old* replaced by
1081 *new*. If the optional argument *count* is given, only the first *count* 1229 *new*. If the optional argument *count* is given, only the first *count*
1082 occurrences are replaced. 1230 occurrences are replaced.
1083 1231
1084 1232
1085 .. method:: str.rfind(sub [,start [,end]]) 1233 .. method:: str.rfind(sub[, start[, end]])
1086 1234
1087 Return the highest index in the string where substring *sub* is found, such 1235 Return the highest index in the string where substring *sub* is found, such
1088 that *sub* is contained within ``s[start:end]``. Optional arguments *start* 1236 that *sub* is contained within ``s[start:end]``. Optional arguments *start*
1089 and *end* are interpreted as in slice notation. Return ``-1`` on failure. 1237 and *end* are interpreted as in slice notation. Return ``-1`` on failure.
1090 1238
1091 1239
1092 .. method:: str.rindex(sub[, start[, end]]) 1240 .. method:: str.rindex(sub[, start[, end]])
1093 1241
1094 Like :meth:`rfind` but raises :exc:`ValueError` when the substring *sub* is n ot 1242 Like :meth:`rfind` but raises :exc:`ValueError` when the substring *sub* is n ot
1095 found. 1243 found.
1096 1244
1097 1245
1098 .. method:: str.rjust(width[, fillchar]) 1246 .. method:: str.rjust(width[, fillchar])
1099 1247
1100 Return the string right justified in a string of length *width*. Padding is d one 1248 Return the string right justified in a string of length *width*. Padding is d one
1101 using the specified *fillchar* (default is a space). The original string is 1249 using the specified *fillchar* (default is a space). The original string is
1102 returned if *width* is less than ``len(s)``. 1250 returned if *width* is less than ``len(s)``.
1103
1104 .. versionchanged:: 2.4
1105 Support for the *fillchar* argument.
1106 1251
1107 1252
1108 .. method:: str.rpartition(sep) 1253 .. method:: str.rpartition(sep)
1109 1254
1110 Split the string at the last occurrence of *sep*, and return a 3-tuple 1255 Split the string at the last occurrence of *sep*, and return a 3-tuple
1111 containing the part before the separator, the separator itself, and the part 1256 containing the part before the separator, the separator itself, and the part
1112 after the separator. If the separator is not found, return a 3-tuple contain ing 1257 after the separator. If the separator is not found, return a 3-tuple contain ing
1113 two empty strings, followed by the string itself. 1258 two empty strings, followed by the string itself.
1114 1259
1115 .. versionadded:: 2.5 1260
1116 1261 .. method:: str.rsplit([sep[, maxsplit]])
1117
1118 .. method:: str.rsplit([sep [,maxsplit]])
1119 1262
1120 Return a list of the words in the string, using *sep* as the delimiter string . 1263 Return a list of the words in the string, using *sep* as the delimiter string .
1121 If *maxsplit* is given, at most *maxsplit* splits are done, the *rightmost* 1264 If *maxsplit* is given, at most *maxsplit* splits are done, the *rightmost*
1122 ones. If *sep* is not specified or ``None``, any whitespace string is a 1265 ones. If *sep* is not specified or ``None``, any whitespace string is a
1123 separator. Except for splitting from the right, :meth:`rsplit` behaves like 1266 separator. Except for splitting from the right, :meth:`rsplit` behaves like
1124 :meth:`split` which is described in detail below. 1267 :meth:`split` which is described in detail below.
1125 1268
1126 .. versionadded:: 2.4
1127
1128 1269
1129 .. method:: str.rstrip([chars]) 1270 .. method:: str.rstrip([chars])
1130 1271
1131 Return a copy of the string with trailing characters removed. The *chars* 1272 Return a copy of the string with trailing characters removed. The *chars*
1132 argument is a string specifying the set of characters to be removed. If omit ted 1273 argument is a string specifying the set of characters to be removed. If omit ted
1133 or ``None``, the *chars* argument defaults to removing whitespace. The *char s* 1274 or ``None``, the *chars* argument defaults to removing whitespace. The *char s*
1134 argument is not a suffix; rather, all combinations of its values are stripped : 1275 argument is not a suffix; rather, all combinations of its values are stripped :
1135 1276
1136 >>> ' spacious '.rstrip() 1277 >>> ' spacious '.rstrip()
1137 ' spacious' 1278 ' spacious'
1138 >>> 'mississippi'.rstrip('ipz') 1279 >>> 'mississippi'.rstrip('ipz')
1139 'mississ' 1280 'mississ'
1140
1141 .. versionchanged:: 2.2.2
1142 Support for the *chars* argument.
1143 1281
1144 1282
1145 .. method:: str.split([sep[, maxsplit]]) 1283 .. method:: str.split([sep[, maxsplit]])
1146 1284
1147 Return a list of the words in the string, using *sep* as the delimiter 1285 Return a list of the words in the string, using *sep* as the delimiter
1148 string. If *maxsplit* is given, at most *maxsplit* splits are done (thus, 1286 string. If *maxsplit* is given, at most *maxsplit* splits are done (thus,
1149 the list will have at most ``maxsplit+1`` elements). If *maxsplit* is not 1287 the list will have at most ``maxsplit+1`` elements). If *maxsplit* is not
1150 specified, then there is no limit on the number of splits (all possible 1288 specified, then there is no limit on the number of splits (all possible
1151 splits are made). 1289 splits are made).
1152 1290
(...skipping 21 matching lines...) Expand all
1174 true. 1312 true.
1175 1313
1176 1314
1177 .. method:: str.startswith(prefix[, start[, end]]) 1315 .. method:: str.startswith(prefix[, start[, end]])
1178 1316
1179 Return ``True`` if string starts with the *prefix*, otherwise return ``False` `. 1317 Return ``True`` if string starts with the *prefix*, otherwise return ``False` `.
1180 *prefix* can also be a tuple of prefixes to look for. With optional *start*, 1318 *prefix* can also be a tuple of prefixes to look for. With optional *start*,
1181 test string beginning at that position. With optional *end*, stop comparing 1319 test string beginning at that position. With optional *end*, stop comparing
1182 string at that position. 1320 string at that position.
1183 1321
1184 .. versionchanged:: 2.5
1185 Accept tuples as *prefix*.
1186
1187 1322
1188 .. method:: str.strip([chars]) 1323 .. method:: str.strip([chars])
1189 1324
1190 Return a copy of the string with the leading and trailing characters removed. 1325 Return a copy of the string with the leading and trailing characters removed.
1191 The *chars* argument is a string specifying the set of characters to be remov ed. 1326 The *chars* argument is a string specifying the set of characters to be remov ed.
1192 If omitted or ``None``, the *chars* argument defaults to removing whitespace. 1327 If omitted or ``None``, the *chars* argument defaults to removing whitespace.
1193 The *chars* argument is not a prefix or suffix; rather, all combinations of i ts 1328 The *chars* argument is not a prefix or suffix; rather, all combinations of i ts
1194 values are stripped: 1329 values are stripped:
1195 1330
1196 >>> ' spacious '.strip() 1331 >>> ' spacious '.strip()
1197 'spacious' 1332 'spacious'
1198 >>> 'www.example.com'.strip('cmowz.') 1333 >>> 'www.example.com'.strip('cmowz.')
1199 'example' 1334 'example'
1200 1335
1201 .. versionchanged:: 2.2.2
1202 Support for the *chars* argument.
1203
1204 1336
1205 .. method:: str.swapcase() 1337 .. method:: str.swapcase()
1206 1338
1207 Return a copy of the string with uppercase characters converted to lowercase and 1339 Return a copy of the string with uppercase characters converted to lowercase and
1208 vice versa. 1340 vice versa.
1209
1210 For 8-bit strings, this method is locale-dependent.
1211 1341
1212 1342
1213 .. method:: str.title() 1343 .. method:: str.title()
1214 1344
1215 Return a titlecased version of the string where words start with an uppercase 1345 Return a titlecased version of the string where words start with an uppercase
1216 character and the remaining characters are lowercase. 1346 character and the remaining characters are lowercase.
1217 1347
1218 The algorithm uses a simple language-independent definition of a word as 1348 The algorithm uses a simple language-independent definition of a word as
1219 groups of consecutive letters. The definition works in many contexts but 1349 groups of consecutive letters. The definition works in many contexts but
1220 it means that apostrophes in contractions and possessives form word 1350 it means that apostrophes in contractions and possessives form word
1221 boundaries, which may not be the desired result:: 1351 boundaries, which may not be the desired result::
1222 1352
1223 >>> "they're bill's friends from the UK".title() 1353 >>> "they're bill's friends from the UK".title()
1224 "They'Re Bill'S Friends From The Uk" 1354 "They'Re Bill'S Friends From The Uk"
1225 1355
1226 A workaround for apostrophes can be constructed using regular expressions:: 1356 A workaround for apostrophes can be constructed using regular expressions::
1227 1357
1228 >>> import re 1358 >>> import re
1229 >>> def titlecase(s): 1359 >>> def titlecase(s):
1230 return re.sub(r"[A-Za-z]+('[A-Za-z]+)?", 1360 return re.sub(r"[A-Za-z]+('[A-Za-z]+)?",
1231 lambda mo: mo.group(0)[0].upper() + 1361 lambda mo: mo.group(0)[0].upper() +
1232 mo.group(0)[1:].lower(), 1362 mo.group(0)[1:].lower(),
1233 s) 1363 s)
1234 1364
1235 >>> titlecase("they're bill's friends.") 1365 >>> titlecase("they're bill's friends.")
1236 "They're Bill's Friends." 1366 "They're Bill's Friends."
1237 1367
1238 For 8-bit strings, this method is locale-dependent. 1368
1239 1369 .. method:: str.translate(map)
1240 1370
1241 .. method:: str.translate(table[, deletechars]) 1371 Return a copy of the *s* where all characters have been mapped through the
1242 1372 *map* which must be a dictionary of Unicode ordinals (integers) to Unicode
1243 Return a copy of the string where all characters occurring in the optional 1373 ordinals, strings or ``None``. Unmapped characters are left untouched.
1244 argument *deletechars* are removed, and the remaining characters have been 1374 Characters mapped to ``None`` are deleted.
1245 mapped through the given translation table, which must be a string of length 1375
1246 256. 1376 You can use :meth:`str.maketrans` to create a translation map from
1247 1377 character-to-character mappings in different formats.
1248 You can use the :func:`~string.maketrans` helper function in the :mod:`string ` 1378
1249 module to create a translation table. For string objects, set the *table* 1379 .. note::
1250 argument to ``None`` for translations that only delete characters: 1380
1251 1381 An even more flexible approach is to create a custom character mapping
1252 >>> 'read this short text'.translate(None, 'aeiou') 1382 codec using the :mod:`codecs` module (see :mod:`encodings.cp1251` for an
1253 'rd ths shrt txt' 1383 example).
1254
1255 .. versionadded:: 2.6
1256 Support for a ``None`` *table* argument.
1257
1258 For Unicode objects, the :meth:`translate` method does not accept the optiona l
1259 *deletechars* argument. Instead, it returns a copy of the *s* where all
1260 characters have been mapped through the given translation table which must be a
1261 mapping of Unicode ordinals to Unicode ordinals, Unicode strings or ``None``.
1262 Unmapped characters are left untouched. Characters mapped to ``None`` are
1263 deleted. Note, a more flexible approach is to create a custom character mapp ing
1264 codec using the :mod:`codecs` module (see :mod:`encodings.cp1251` for an
1265 example).
1266 1384
1267 1385
1268 .. method:: str.upper() 1386 .. method:: str.upper()
1269 1387
1270 Return a copy of the string converted to uppercase. 1388 Return a copy of the string converted to uppercase.
1271
1272 For 8-bit strings, this method is locale-dependent.
1273 1389
1274 1390
1275 .. method:: str.zfill(width) 1391 .. method:: str.zfill(width)
1276 1392
1277 Return the numeric string left filled with zeros in a string of length 1393 Return the numeric string left filled with zeros in a string of length
1278 *width*. A sign prefix is handled correctly. The original string is 1394 *width*. A sign prefix is handled correctly. The original string is
1279 returned if *width* is less than ``len(s)``. 1395 returned if *width* is less than ``len(s)``.
1280 1396
1281 1397
1282 .. versionadded:: 2.2.2 1398
1283 1399 .. _old-string-formatting:
1284 The following methods are present only on unicode objects: 1400
1285 1401 Old String Formatting Operations
1286 .. method:: unicode.isnumeric() 1402 --------------------------------
1287
1288 Return ``True`` if there are only numeric characters in S, ``False``
1289 otherwise. Numeric characters include digit characters, and all characters
1290 that have the Unicode numeric value property, e.g. U+2155,
1291 VULGAR FRACTION ONE FIFTH.
1292
1293 .. method:: unicode.isdecimal()
1294
1295 Return ``True`` if there are only decimal characters in S, ``False``
1296 otherwise. Decimal characters include digit characters, and all characters
1297 that that can be used to form decimal-radix numbers, e.g. U+0660,
1298 ARABIC-INDIC DIGIT ZERO.
1299
1300
1301 .. _string-formatting:
1302
1303 String Formatting Operations
1304 ----------------------------
1305 1403
1306 .. index:: 1404 .. index::
1307 single: formatting, string (%) 1405 single: formatting, string (%)
1308 single: interpolation, string (%) 1406 single: interpolation, string (%)
1309 single: string; formatting 1407 single: string; formatting
1310 single: string; interpolation 1408 single: string; interpolation
1311 single: printf-style formatting 1409 single: printf-style formatting
1312 single: sprintf-style formatting 1410 single: sprintf-style formatting
1313 single: % formatting 1411 single: % formatting
1314 single: % interpolation 1412 single: % interpolation
1315 1413
1316 String and Unicode objects have one unique built-in operation: the ``%`` 1414 .. XXX is the note enough?
1317 operator (modulo). This is also known as the string *formatting* or 1415
1318 *interpolation* operator. Given ``format % values`` (where *format* is a string 1416 .. note::
1319 or Unicode object), ``%`` conversion specifications in *format* are replaced 1417
1320 with zero or more elements of *values*. The effect is similar to the using 1418 The formatting operations described here are obsolete and may go away in futu re
1321 :cfunc:`sprintf` in the C language. If *format* is a Unicode object, or if any 1419 versions of Python. Use the new :ref:`string-formatting` in new code.
1322 of the objects being converted using the ``%s`` conversion are Unicode objects, 1420
1323 the result will also be a Unicode object. 1421 String objects have one unique built-in operation: the ``%`` operator (modulo).
1422 This is also known as the string *formatting* or *interpolation* operator.
1423 Given ``format % values`` (where *format* is a string), ``%`` conversion
1424 specifications in *format* are replaced with zero or more elements of *values*.
1425 The effect is similar to the using :c:func:`sprintf` in the C language.
1324 1426
1325 If *format* requires a single argument, *values* may be a single non-tuple 1427 If *format* requires a single argument, *values* may be a single non-tuple
1326 object. [#]_ Otherwise, *values* must be a tuple with exactly the number of 1428 object. [#]_ Otherwise, *values* must be a tuple with exactly the number of
1327 items specified by the format string, or a single mapping object (for example, a 1429 items specified by the format string, or a single mapping object (for example, a
1328 dictionary). 1430 dictionary).
1329 1431
1330 A conversion specifier contains two or more characters and has the following 1432 A conversion specifier contains two or more characters and has the following
1331 components, which must occur in this order: 1433 components, which must occur in this order:
1332 1434
1333 #. The ``'%'`` character, which marks the start of the specifier. 1435 #. The ``'%'`` character, which marks the start of the specifier.
(...skipping 15 matching lines...) Expand all
1349 1451
1350 #. Length modifier (optional). 1452 #. Length modifier (optional).
1351 1453
1352 #. Conversion type. 1454 #. Conversion type.
1353 1455
1354 When the right argument is a dictionary (or other mapping type), then the 1456 When the right argument is a dictionary (or other mapping type), then the
1355 formats in the string *must* include a parenthesised mapping key into that 1457 formats in the string *must* include a parenthesised mapping key into that
1356 dictionary inserted immediately after the ``'%'`` character. The mapping key 1458 dictionary inserted immediately after the ``'%'`` character. The mapping key
1357 selects the value to be formatted from the mapping. For example: 1459 selects the value to be formatted from the mapping. For example:
1358 1460
1359 >>> print '%(language)s has %(number)03d quote types.' % \ 1461 >>> print('%(language)s has %(number)03d quote types.' %
1360 ... {"language": "Python", "number": 2} 1462 ... {'language': "Python", "number": 2})
1361 Python has 002 quote types. 1463 Python has 002 quote types.
1362 1464
1363 In this case no ``*`` specifiers may occur in a format (since they require a 1465 In this case no ``*`` specifiers may occur in a format (since they require a
1364 sequential parameter list). 1466 sequential parameter list).
1365 1467
1366 The conversion flag characters are: 1468 The conversion flag characters are:
1367 1469
1368 +---------+--------------------------------------------------------------------- + 1470 +---------+--------------------------------------------------------------------- +
1369 | Flag | Meaning | 1471 | Flag | Meaning |
1370 +=========+===================================================================== + 1472 +=========+===================================================================== +
(...skipping 47 matching lines...) Expand 10 before | Expand all | Expand 10 after
1418 | ``'G'`` | Floating point format. Uses uppercase exponential | \(4) | 1520 | ``'G'`` | Floating point format. Uses uppercase exponential | \(4) |
1419 | | format if exponent is less than -4 or not less than | | 1521 | | format if exponent is less than -4 or not less than | |
1420 | | precision, decimal format otherwise. | | 1522 | | precision, decimal format otherwise. | |
1421 +------------+-----------------------------------------------------+-------+ 1523 +------------+-----------------------------------------------------+-------+
1422 | ``'c'`` | Single character (accepts integer or single | | 1524 | ``'c'`` | Single character (accepts integer or single | |
1423 | | character string). | | 1525 | | character string). | |
1424 +------------+-----------------------------------------------------+-------+ 1526 +------------+-----------------------------------------------------+-------+
1425 | ``'r'`` | String (converts any Python object using | \(5) | 1527 | ``'r'`` | String (converts any Python object using | \(5) |
1426 | | :func:`repr`). | | 1528 | | :func:`repr`). | |
1427 +------------+-----------------------------------------------------+-------+ 1529 +------------+-----------------------------------------------------+-------+
1428 | ``'s'`` | String (converts any Python object using | \(6) | 1530 | ``'s'`` | String (converts any Python object using | |
1429 | | :func:`str`). | | 1531 | | :func:`str`). | |
1430 +------------+-----------------------------------------------------+-------+ 1532 +------------+-----------------------------------------------------+-------+
1431 | ``'%'`` | No argument is converted, results in a ``'%'`` | | 1533 | ``'%'`` | No argument is converted, results in a ``'%'`` | |
1432 | | character in the result. | | 1534 | | character in the result. | |
1433 +------------+-----------------------------------------------------+-------+ 1535 +------------+-----------------------------------------------------+-------+
1434 1536
1435 Notes: 1537 Notes:
1436 1538
1437 (1) 1539 (1)
1438 The alternate form causes a leading zero (``'0'``) to be inserted between 1540 The alternate form causes a leading zero (``'0'``) to be inserted between
(...skipping 14 matching lines...) Expand all
1453 defaults to 6. 1555 defaults to 6.
1454 1556
1455 (4) 1557 (4)
1456 The alternate form causes the result to always contain a decimal point, and 1558 The alternate form causes the result to always contain a decimal point, and
1457 trailing zeroes are not removed as they would otherwise be. 1559 trailing zeroes are not removed as they would otherwise be.
1458 1560
1459 The precision determines the number of significant digits before and after th e 1561 The precision determines the number of significant digits before and after th e
1460 decimal point and defaults to 6. 1562 decimal point and defaults to 6.
1461 1563
1462 (5) 1564 (5)
1463 The ``%r`` conversion was added in Python 2.0.
1464
1465 The precision determines the maximal number of characters used. 1565 The precision determines the maximal number of characters used.
1466 1566
1467 (6)
1468 If the object or format provided is a :class:`unicode` string, the resulting
1469 string will also be :class:`unicode`.
1470
1471 The precision determines the maximal number of characters used.
1472 1567
1473 (7) 1568 (7)
1474 See :pep:`237`. 1569 See :pep:`237`.
1475 1570
1476 Since Python strings have an explicit length, ``%s`` conversions do not assume 1571 Since Python strings have an explicit length, ``%s`` conversions do not assume
1477 that ``'\0'`` is the end of the string. 1572 that ``'\0'`` is the end of the string.
1478 1573
1479 .. XXX Examples? 1574 .. XXX Examples?
1480 1575
1481 .. versionchanged:: 2.7 1576 .. versionchanged:: 3.1
1482 ``%f`` conversions for numbers whose absolute value is over 1e50 are no 1577 ``%f`` conversions for numbers whose absolute value is over 1e50 are no
1483 longer replaced by ``%g`` conversions. 1578 longer replaced by ``%g`` conversions.
1484 1579
1485 .. index:: 1580 .. index::
1486 module: string 1581 module: string
1487 module: re 1582 module: re
1488 1583
1489 Additional string operations are defined in standard modules :mod:`string` and 1584 Additional string operations are defined in standard modules :mod:`string` and
1490 :mod:`re`. 1585 :mod:`re`.
1491 1586
1492 1587
1493 .. _typesseq-xrange: 1588 .. _typesseq-range:
1494 1589
1495 XRange Type 1590 Range Type
1496 ----------- 1591 ----------
1497 1592
1498 .. index:: object: xrange 1593 .. index:: object: range
1499 1594
1500 The :class:`xrange` type is an immutable sequence which is commonly used for 1595 The :class:`range` type is an immutable sequence which is commonly used for
1501 looping. The advantage of the :class:`xrange` type is that an :class:`xrange` 1596 looping. The advantage of the :class:`range` type is that an :class:`range`
1502 object will always take the same amount of memory, no matter the size of the 1597 object will always take the same amount of memory, no matter the size of the
1503 range it represents. There are no consistent performance advantages. 1598 range it represents.
1504 1599
1505 XRange objects have very little behavior: they only support indexing, iteration, 1600 Range objects have relatively little behavior: they support indexing, contains,
1506 and the :func:`len` function. 1601 iteration, the :func:`len` function, and the following methods:
1507 1602
1603 .. method:: range.count(x)
1604
1605 Return the number of *i*'s for which ``s[i] == x``.
1606
1607 .. versionadded:: 3.2
1608
1609 .. method:: range.index(x)
1610
1611 Return the smallest *i* such that ``s[i] == x``. Raises
1612 :exc:`ValueError` when *x* is not in the range.
1613
1614 .. versionadded:: 3.2
1508 1615
1509 .. _typesseq-mutable: 1616 .. _typesseq-mutable:
1510 1617
1511 Mutable Sequence Types 1618 Mutable Sequence Types
1512 ---------------------- 1619 ----------------------
1513 1620
1514 .. index:: 1621 .. index::
1515 triple: mutable; sequence; types 1622 triple: mutable; sequence; types
1516 object: list 1623 object: list
1517 1624 object: bytearray
1518 List and :class:`bytearray` objects support additional operations that allow 1625
1519 in-place modification of the object. Other mutable sequence types (when added 1626 List and bytearray objects support additional operations that allow in-place
1520 to the language) should also support these operations. Strings and tuples 1627 modification of the object. Other mutable sequence types (when added to the
1521 are immutable sequence types: such objects cannot be modified once created. 1628 language) should also support these operations. Strings and tuples are
1522 The following operations are defined on mutable sequence types (where *x* is 1629 immutable sequence types: such objects cannot be modified once created. The
1523 an arbitrary object): 1630 following operations are defined on mutable sequence types (where *x* is an
1631 arbitrary object).
1632
1633 Note that while lists allow their items to be of any type, bytearray object
1634 "items" are all integers in the range 0 <= x < 256.
1524 1635
1525 .. index:: 1636 .. index::
1526 triple: operations on; sequence; types 1637 triple: operations on; sequence; types
1527 triple: operations on; list; type 1638 triple: operations on; list; type
1528 pair: subscript; assignment 1639 pair: subscript; assignment
1529 pair: slice; assignment 1640 pair: slice; assignment
1530 pair: extended slice; assignment
1531 statement: del 1641 statement: del
1532 single: append() (list method) 1642 single: append() (sequence method)
1533 single: extend() (list method) 1643 single: extend() (sequence method)
1534 single: count() (list method) 1644 single: count() (sequence method)
1535 single: index() (list method) 1645 single: clear() (sequence method)
1536 single: insert() (list method) 1646 single: copy() (sequence method)
1537 single: pop() (list method) 1647 single: index() (sequence method)
1538 single: remove() (list method) 1648 single: insert() (sequence method)
1539 single: reverse() (list method) 1649 single: pop() (sequence method)
1540 single: sort() (list method) 1650 single: remove() (sequence method)
1651 single: reverse() (sequence method)
1652 single: sort() (sequence method)
1541 1653
1542 +------------------------------+--------------------------------+--------------- ------+ 1654 +------------------------------+--------------------------------+--------------- ------+
1543 | Operation | Result | Notes | 1655 | Operation | Result | Notes |
1544 +==============================+================================+=============== ======+ 1656 +==============================+================================+=============== ======+
1545 | ``s[i] = x`` | item *i* of *s* is replaced by | | 1657 | ``s[i] = x`` | item *i* of *s* is replaced by | |
1546 | | *x* | | 1658 | | *x* | |
1547 +------------------------------+--------------------------------+--------------- ------+ 1659 +------------------------------+--------------------------------+--------------- ------+
1548 | ``s[i:j] = t`` | slice of *s* from *i* to *j* | | 1660 | ``s[i:j] = t`` | slice of *s* from *i* to *j* | |
1549 | | is replaced by the contents of | | 1661 | | is replaced by the contents of | |
1550 | | the iterable *t* | | 1662 | | the iterable *t* | |
1551 +------------------------------+--------------------------------+--------------- ------+ 1663 +------------------------------+--------------------------------+--------------- ------+
1552 | ``del s[i:j]`` | same as ``s[i:j] = []`` | | 1664 | ``del s[i:j]`` | same as ``s[i:j] = []`` | |
1553 +------------------------------+--------------------------------+--------------- ------+ 1665 +------------------------------+--------------------------------+--------------- ------+
1554 | ``s[i:j:k] = t`` | the elements of ``s[i:j:k]`` | \(1) | 1666 | ``s[i:j:k] = t`` | the elements of ``s[i:j:k]`` | \(1) |
1555 | | are replaced by those of *t* | | 1667 | | are replaced by those of *t* | |
1556 +------------------------------+--------------------------------+--------------- ------+ 1668 +------------------------------+--------------------------------+--------------- ------+
1557 | ``del s[i:j:k]`` | removes the elements of | | 1669 | ``del s[i:j:k]`` | removes the elements of | |
1558 | | ``s[i:j:k]`` from the list | | 1670 | | ``s[i:j:k]`` from the list | |
1559 +------------------------------+--------------------------------+--------------- ------+ 1671 +------------------------------+--------------------------------+--------------- ------+
1560 | ``s.append(x)`` | same as ``s[len(s):len(s)] = | \(2) | 1672 | ``s.append(x)`` | same as ``s[len(s):len(s)] = | |
1561 | | [x]`` | | 1673 | | [x]`` | |
1562 +------------------------------+--------------------------------+--------------- ------+ 1674 +------------------------------+--------------------------------+--------------- ------+
1563 | ``s.extend(x)`` | same as ``s[len(s):len(s)] = | \(3) | 1675 | ``s.extend(x)`` | same as ``s[len(s):len(s)] = | \(2) |
1564 | | x`` | | 1676 | | x`` | |
1677 +------------------------------+--------------------------------+--------------- ------+
1678 | ``s.clear()`` | remove all items from ``s`` | |
1679 | | | |
1680 +------------------------------+--------------------------------+--------------- ------+
1681 | ``s.copy()`` | return a shallow copy of ``s`` | |
1682 | | | |
1565 +------------------------------+--------------------------------+--------------- ------+ 1683 +------------------------------+--------------------------------+--------------- ------+
1566 | ``s.count(x)`` | return number of *i*'s for | | 1684 | ``s.count(x)`` | return number of *i*'s for | |
1567 | | which ``s[i] == x`` | | 1685 | | which ``s[i] == x`` | |
1568 +------------------------------+--------------------------------+--------------- ------+ 1686 +------------------------------+--------------------------------+--------------- ------+
1569 | ``s.index(x[, i[, j]])`` | return smallest *k* such that | \(4) | 1687 | ``s.index(x[, i[, j]])`` | return smallest *k* such that | \(3) |
1570 | | ``s[k] == x`` and ``i <= k < | | 1688 | | ``s[k] == x`` and ``i <= k < | |
1571 | | j`` | | 1689 | | j`` | |
1572 +------------------------------+--------------------------------+--------------- ------+ 1690 +------------------------------+--------------------------------+--------------- ------+
1573 | ``s.insert(i, x)`` | same as ``s[i:i] = [x]`` | \(5) | 1691 | ``s.insert(i, x)`` | same as ``s[i:i] = [x]`` | \(4) |
1574 +------------------------------+--------------------------------+--------------- ------+ 1692 +------------------------------+--------------------------------+--------------- ------+
1575 | ``s.pop([i])`` | same as ``x = s[i]; del s[i]; | \(6) | 1693 | ``s.pop([i])`` | same as ``x = s[i]; del s[i]; | \(5) |
1576 | | return x`` | | 1694 | | return x`` | |
1577 +------------------------------+--------------------------------+--------------- ------+ 1695 +------------------------------+--------------------------------+--------------- ------+
1578 | ``s.remove(x)`` | same as ``del s[s.index(x)]`` | \(4) | 1696 | ``s.remove(x)`` | same as ``del s[s.index(x)]`` | \(3) |
1579 +------------------------------+--------------------------------+--------------- ------+ 1697 +------------------------------+--------------------------------+--------------- ------+
1580 | ``s.reverse()`` | reverses the items of *s* in | \(7) | 1698 | ``s.reverse()`` | reverses the items of *s* in | \(6) |
1581 | | place | | 1699 | | place | |
1582 +------------------------------+--------------------------------+--------------- ------+ 1700 +------------------------------+--------------------------------+--------------- ------+
1583 | ``s.sort([cmp[, key[, | sort the items of *s* in place | (7)(8)(9)(10) | 1701 | ``s.sort([key[, reverse]])`` | sort the items of *s* in place | (6), (7), (8) |
1584 | reverse]]])`` | | |
1585 +------------------------------+--------------------------------+--------------- ------+ 1702 +------------------------------+--------------------------------+--------------- ------+
1586 1703
1704
1587 Notes: 1705 Notes:
1588 1706
1589 (1) 1707 (1)
1590 *t* must have the same length as the slice it is replacing. 1708 *t* must have the same length as the slice it is replacing.
1591 1709
1592 (2) 1710 (2)
1593 The C implementation of Python has historically accepted multiple parameters and 1711 *x* can be any iterable object.
1594 implicitly joined them into a tuple; this no longer works in Python 2.0. Use of
1595 this misfeature has been deprecated since Python 1.4.
1596 1712
1597 (3) 1713 (3)
1598 *x* can be any iterable object.
1599
1600 (4)
1601 Raises :exc:`ValueError` when *x* is not found in *s*. When a negative index is 1714 Raises :exc:`ValueError` when *x* is not found in *s*. When a negative index is
1602 passed as the second or third parameter to the :meth:`index` method, the list 1715 passed as the second or third parameter to the :meth:`index` method, the sequ ence
1603 length is added, as for slice indices. If it is still negative, it is trunca ted 1716 length is added, as for slice indices. If it is still negative, it is trunca ted
1604 to zero, as for slice indices. 1717 to zero, as for slice indices.
1605 1718
1606 .. versionchanged:: 2.3 1719 (4)
1607 Previously, :meth:`index` didn't have arguments for specifying start and s top 1720 When a negative index is passed as the first parameter to the :meth:`insert`
1608 positions. 1721 method, the sequence length is added, as for slice indices. If it is still
1722 negative, it is truncated to zero, as for slice indices.
1609 1723
1610 (5) 1724 (5)
1611 When a negative index is passed as the first parameter to the :meth:`insert` 1725 The optional argument *i* defaults to ``-1``, so that by default the last
1612 method, the list length is added, as for slice indices. If it is still 1726 item is removed and returned.
1613 negative, it is truncated to zero, as for slice indices.
1614
1615 .. versionchanged:: 2.3
1616 Previously, all negative indices were truncated to zero.
1617 1727
1618 (6) 1728 (6)
1619 The :meth:`pop` method is only supported by the list and array types. The 1729 The :meth:`sort` and :meth:`reverse` methods modify the sequence in place for
1620 optional argument *i* defaults to ``-1``, so that by default the last item is 1730 economy of space when sorting or reversing a large sequence. To remind you
1621 removed and returned. 1731 that they operate by side effect, they don't return the sorted or reversed
1732 sequence.
1622 1733
1623 (7) 1734 (7)
1624 The :meth:`sort` and :meth:`reverse` methods modify the list in place for
1625 economy of space when sorting or reversing a large list. To remind you that
1626 they operate by side effect, they don't return the sorted or reversed list.
1627
1628 (8)
1629 The :meth:`sort` method takes optional arguments for controlling the 1735 The :meth:`sort` method takes optional arguments for controlling the
1630 comparisons. 1736 comparisons. Each must be specified as a keyword argument.
1631
1632 *cmp* specifies a custom comparison function of two arguments (list items) wh ich
1633 should return a negative, zero or positive number depending on whether the fi rst
1634 argument is considered smaller than, equal to, or larger than the second
1635 argument: ``cmp=lambda x,y: cmp(x.lower(), y.lower())``. The default value
1636 is ``None``.
1637 1737
1638 *key* specifies a function of one argument that is used to extract a comparis on 1738 *key* specifies a function of one argument that is used to extract a comparis on
1639 key from each list element: ``key=str.lower``. The default value is ``None`` . 1739 key from each list element: ``key=str.lower``. The default value is ``None`` .
1740 Use :func:`functools.cmp_to_key` to convert an
1741 old-style *cmp* function to a *key* function.
1742
1640 1743
1641 *reverse* is a boolean value. If set to ``True``, then the list elements are 1744 *reverse* is a boolean value. If set to ``True``, then the list elements are
1642 sorted as if each comparison were reversed. 1745 sorted as if each comparison were reversed.
1643 1746
1644 In general, the *key* and *reverse* conversion processes are much faster than 1747 The :meth:`sort` method is guaranteed to be stable. A
1645 specifying an equivalent *cmp* function. This is because *cmp* is called
1646 multiple times for each list element while *key* and *reverse* touch each
1647 element only once. Use :func:`functools.cmp_to_key` to convert an
1648 old-style *cmp* function to a *key* function.
1649
1650 .. versionchanged:: 2.3
1651 Support for ``None`` as an equivalent to omitting *cmp* was added.
1652
1653 .. versionchanged:: 2.4
1654 Support for *key* and *reverse* was added.
1655
1656 (9)
1657 Starting with Python 2.3, the :meth:`sort` method is guaranteed to be stable. A
1658 sort is stable if it guarantees not to change the relative order of elements 1748 sort is stable if it guarantees not to change the relative order of elements
1659 that compare equal --- this is helpful for sorting in multiple passes (for 1749 that compare equal --- this is helpful for sorting in multiple passes (for
1660 example, sort by department, then by salary grade). 1750 example, sort by department, then by salary grade).
1661 1751
1662 (10)
1663 .. impl-detail:: 1752 .. impl-detail::
1664 1753
1665 While a list is being sorted, the effect of attempting to mutate, or even 1754 While a list is being sorted, the effect of attempting to mutate, or even
1666 inspect, the list is undefined. The C implementation of Python 2.3 and 1755 inspect, the list is undefined. The C implementation of Python makes the
1667 newer makes the list appear empty for the duration, and raises 1756 list appear empty for the duration, and raises :exc:`ValueError` if it can
1668 :exc:`ValueError` if it can detect that the list has been mutated during a 1757 detect that the list has been mutated during a sort.
1669 sort. 1758
1759 (8)
1760 :meth:`sort` is not supported by :class:`bytearray` objects.
1761
1762 .. versionadded:: 3.3
1763 :meth:`clear` and :meth:`!copy` methods.
1764
1765
1766 .. _bytes-methods:
1767
1768 Bytes and Byte Array Methods
1769 ----------------------------
1770
1771 .. index:: pair: bytes; methods
1772 pair: bytearray; methods
1773
1774 Bytes and bytearray objects, being "strings of bytes", have all methods found on
1775 strings, with the exception of :func:`encode`, :func:`format` and
1776 :func:`isidentifier`, which do not make sense with these types. For converting
1777 the objects to strings, they have a :func:`decode` method.
1778
1779 Wherever one of these methods needs to interpret the bytes as characters
1780 (e.g. the :func:`is...` methods), the ASCII character set is assumed.
1781
1782 .. note::
1783
1784 The methods on bytes and bytearray objects don't accept strings as their
1785 arguments, just as the methods on strings don't accept bytes as their
1786 arguments. For example, you have to write ::
1787
1788 a = "abc"
1789 b = a.replace("a", "f")
1790
1791 and ::
1792
1793 a = b"abc"
1794 b = a.replace(b"a", b"f")
1795
1796
1797 .. method:: bytes.decode(encoding="utf-8", errors="strict")
1798 bytearray.decode(encoding="utf-8", errors="strict")
1799
1800 Return a string decoded from the given bytes. Default encoding is
1801 ``'utf-8'``. *errors* may be given to set a different
1802 error handling scheme. The default for *errors* is ``'strict'``, meaning
1803 that encoding errors raise a :exc:`UnicodeError`. Other possible values are
1804 ``'ignore'``, ``'replace'`` and any other name registered via
1805 :func:`codecs.register_error`, see section :ref:`codec-base-classes`. For a
1806 list of possible encodings, see section :ref:`standard-encodings`.
1807
1808 .. versionchanged:: 3.1
1809 Added support for keyword arguments.
1810
1811
1812 The bytes and bytearray types have an additional class method:
1813
1814 .. classmethod:: bytes.fromhex(string)
1815 bytearray.fromhex(string)
1816
1817 This :class:`bytes` class method returns a bytes or bytearray object,
1818 decoding the given string object. The string must contain two hexadecimal
1819 digits per byte, spaces are ignored.
1820
1821 >>> bytes.fromhex('f0 f1f2 ')
1822 b'\xf0\xf1\xf2'
1823
1824
1825 The maketrans and translate methods differ in semantics from the versions
1826 available on strings:
1827
1828 .. method:: bytes.translate(table[, delete])
1829 bytearray.translate(table[, delete])
1830
1831 Return a copy of the bytes or bytearray object where all bytes occurring in
1832 the optional argument *delete* are removed, and the remaining bytes have been
1833 mapped through the given translation table, which must be a bytes object of
1834 length 256.
1835
1836 You can use the :func:`bytes.maketrans` method to create a translation table.
1837
1838 Set the *table* argument to ``None`` for translations that only delete
1839 characters::
1840
1841 >>> b'read this short text'.translate(None, b'aeiou')
1842 b'rd ths shrt txt'
1843
1844
1845 .. staticmethod:: bytes.maketrans(from, to)
1846 bytearray.maketrans(from, to)
1847
1848 This static method returns a translation table usable for
1849 :meth:`bytes.translate` that will map each character in *from* into the
1850 character at the same position in *to*; *from* and *to* must be bytes objects
1851 and have the same length.
1852
1853 .. versionadded:: 3.1
1670 1854
1671 1855
1672 .. _types-set: 1856 .. _types-set:
1673 1857
1674 Set Types --- :class:`set`, :class:`frozenset` 1858 Set Types --- :class:`set`, :class:`frozenset`
1675 ============================================== 1859 ==============================================
1676 1860
1677 .. index:: object: set 1861 .. index:: object: set
1678 1862
1679 A :dfn:`set` object is an unordered collection of distinct :term:`hashable` obje cts. 1863 A :dfn:`set` object is an unordered collection of distinct :term:`hashable` obje cts.
1680 Common uses include membership testing, removing duplicates from a sequence, and 1864 Common uses include membership testing, removing duplicates from a sequence, and
1681 computing mathematical operations such as intersection, union, difference, and 1865 computing mathematical operations such as intersection, union, difference, and
1682 symmetric difference. 1866 symmetric difference.
1683 (For other containers see the built in :class:`dict`, :class:`list`, 1867 (For other containers see the built in :class:`dict`, :class:`list`,
1684 and :class:`tuple` classes, and the :mod:`collections` module.) 1868 and :class:`tuple` classes, and the :mod:`collections` module.)
1685 1869
1686
1687 .. versionadded:: 2.4
1688
1689 Like other collections, sets support ``x in set``, ``len(set)``, and ``for x in 1870 Like other collections, sets support ``x in set``, ``len(set)``, and ``for x in
1690 set``. Being an unordered collection, sets do not record element position or 1871 set``. Being an unordered collection, sets do not record element position or
1691 order of insertion. Accordingly, sets do not support indexing, slicing, or 1872 order of insertion. Accordingly, sets do not support indexing, slicing, or
1692 other sequence-like behavior. 1873 other sequence-like behavior.
1693 1874
1694 There are currently two built-in set types, :class:`set` and :class:`frozenset`. 1875 There are currently two built-in set types, :class:`set` and :class:`frozenset`.
1695 The :class:`set` type is mutable --- the contents can be changed using methods 1876 The :class:`set` type is mutable --- the contents can be changed using methods
1696 like :meth:`add` and :meth:`remove`. Since it is mutable, it has no hash value 1877 like :meth:`add` and :meth:`remove`. Since it is mutable, it has no hash value
1697 and cannot be used as either a dictionary key or as an element of another set. 1878 and cannot be used as either a dictionary key or as an element of another set.
1698 The :class:`frozenset` type is immutable and :term:`hashable` --- its contents 1879 The :class:`frozenset` type is immutable and :term:`hashable` --- its contents c annot be
1699 cannot be altered after it is created; it can therefore be used as a dictionary 1880 altered after it is created; it can therefore be used as a dictionary key or as
1700 key or as an element of another set. 1881 an element of another set.
1701 1882
1702 As of Python 2.7, non-empty sets (not frozensets) can be created by placing a 1883 Non-empty sets (not frozensets) can be created by placing a comma-separated list
1703 comma-separated list of elements within braces, for example: ``{'jack', 1884 of elements within braces, for example: ``{'jack', 'sjoerd'}``, in addition to t he
1704 'sjoerd'}``, in addition to the :class:`set` constructor. 1885 :class:`set` constructor.
1705 1886
1706 The constructors for both classes work the same: 1887 The constructors for both classes work the same:
1707 1888
1708 .. class:: set([iterable]) 1889 .. class:: set([iterable])
1709 frozenset([iterable]) 1890 frozenset([iterable])
1710 1891
1711 Return a new set or frozenset object whose elements are taken from 1892 Return a new set or frozenset object whose elements are taken from
1712 *iterable*. The elements of a set must be hashable. To represent sets of 1893 *iterable*. The elements of a set must be hashable. To represent sets of
1713 sets, the inner sets must be :class:`frozenset` objects. If *iterable* is 1894 sets, the inner sets must be :class:`frozenset` objects. If *iterable* is
1714 not specified, a new empty set is returned. 1895 not specified, a new empty set is returned.
(...skipping 11 matching lines...) Expand all
1726 1907
1727 .. describe:: x not in s 1908 .. describe:: x not in s
1728 1909
1729 Test *x* for non-membership in *s*. 1910 Test *x* for non-membership in *s*.
1730 1911
1731 .. method:: isdisjoint(other) 1912 .. method:: isdisjoint(other)
1732 1913
1733 Return True if the set has no elements in common with *other*. Sets are 1914 Return True if the set has no elements in common with *other*. Sets are
1734 disjoint if and only if their intersection is the empty set. 1915 disjoint if and only if their intersection is the empty set.
1735 1916
1736 .. versionadded:: 2.6
1737
1738 .. method:: issubset(other) 1917 .. method:: issubset(other)
1739 set <= other 1918 set <= other
1740 1919
1741 Test whether every element in the set is in *other*. 1920 Test whether every element in the set is in *other*.
1742 1921
1743 .. method:: set < other 1922 .. method:: set < other
1744 1923
1745 Test whether the set is a true subset of *other*, that is, 1924 Test whether the set is a true subset of *other*, that is,
1746 ``set <= other and set != other``. 1925 ``set <= other and set != other``.
1747 1926
1748 .. method:: issuperset(other) 1927 .. method:: issuperset(other)
1749 set >= other 1928 set >= other
1750 1929
1751 Test whether every element in *other* is in the set. 1930 Test whether every element in *other* is in the set.
1752 1931
1753 .. method:: set > other 1932 .. method:: set > other
1754 1933
1755 Test whether the set is a true superset of *other*, that is, ``set >= 1934 Test whether the set is a true superset of *other*, that is, ``set >=
1756 other and set != other``. 1935 other and set != other``.
1757 1936
1758 .. method:: union(other, ...) 1937 .. method:: union(other, ...)
1759 set | other | ... 1938 set | other | ...
1760 1939
1761 Return a new set with elements from the set and all others. 1940 Return a new set with elements from the set and all others.
1762 1941
1763 .. versionchanged:: 2.6
1764 Accepts multiple input iterables.
1765
1766 .. method:: intersection(other, ...) 1942 .. method:: intersection(other, ...)
1767 set & other & ... 1943 set & other & ...
1768 1944
1769 Return a new set with elements common to the set and all others. 1945 Return a new set with elements common to the set and all others.
1770 1946
1771 .. versionchanged:: 2.6
1772 Accepts multiple input iterables.
1773
1774 .. method:: difference(other, ...) 1947 .. method:: difference(other, ...)
1775 set - other - ... 1948 set - other - ...
1776 1949
1777 Return a new set with elements in the set that are not in the others. 1950 Return a new set with elements in the set that are not in the others.
1778
1779 .. versionchanged:: 2.6
1780 Accepts multiple input iterables.
1781 1951
1782 .. method:: symmetric_difference(other) 1952 .. method:: symmetric_difference(other)
1783 set ^ other 1953 set ^ other
1784 1954
1785 Return a new set with elements in either the set or *other* but not both. 1955 Return a new set with elements in either the set or *other* but not both.
1786 1956
1787 .. method:: copy() 1957 .. method:: copy()
1788 1958
1789 Return a new set with a shallow copy of *s*. 1959 Return a new set with a shallow copy of *s*.
1790 1960
(...skipping 12 matching lines...) Expand all
1803 is not equal). A set is greater than another set if and only if the first set 1973 is not equal). A set is greater than another set if and only if the first set
1804 is a proper superset of the second set (is a superset, but is not equal). 1974 is a proper superset of the second set (is a superset, but is not equal).
1805 1975
1806 Instances of :class:`set` are compared to instances of :class:`frozenset` 1976 Instances of :class:`set` are compared to instances of :class:`frozenset`
1807 based on their members. For example, ``set('abc') == frozenset('abc')`` 1977 based on their members. For example, ``set('abc') == frozenset('abc')``
1808 returns ``True`` and so does ``set('abc') in set([frozenset('abc')])``. 1978 returns ``True`` and so does ``set('abc') in set([frozenset('abc')])``.
1809 1979
1810 The subset and equality comparisons do not generalize to a complete ordering 1980 The subset and equality comparisons do not generalize to a complete ordering
1811 function. For example, any two disjoint sets are not equal and are not 1981 function. For example, any two disjoint sets are not equal and are not
1812 subsets of each other, so *all* of the following return ``False``: ``a<b``, 1982 subsets of each other, so *all* of the following return ``False``: ``a<b``,
1813 ``a==b``, or ``a>b``. Accordingly, sets do not implement the :meth:`__cmp__` 1983 ``a==b``, or ``a>b``.
1814 method.
1815 1984
1816 Since sets only define partial ordering (subset relationships), the output of 1985 Since sets only define partial ordering (subset relationships), the output of
1817 the :meth:`list.sort` method is undefined for lists of sets. 1986 the :meth:`list.sort` method is undefined for lists of sets.
1818 1987
1819 Set elements, like dictionary keys, must be :term:`hashable`. 1988 Set elements, like dictionary keys, must be :term:`hashable`.
1820 1989
1821 Binary operations that mix :class:`set` instances with :class:`frozenset` 1990 Binary operations that mix :class:`set` instances with :class:`frozenset`
1822 return the type of the first operand. For example: ``frozenset('ab') | 1991 return the type of the first operand. For example: ``frozenset('ab') |
1823 set('bc')`` returns an instance of :class:`frozenset`. 1992 set('bc')`` returns an instance of :class:`frozenset`.
1824 1993
1825 The following table lists operations available for :class:`set` that do not 1994 The following table lists operations available for :class:`set` that do not
1826 apply to immutable instances of :class:`frozenset`: 1995 apply to immutable instances of :class:`frozenset`:
1827 1996
1828 .. method:: update(other, ...) 1997 .. method:: update(other, ...)
1829 set |= other | ... 1998 set |= other | ...
1830 1999
1831 Update the set, adding elements from all others. 2000 Update the set, adding elements from all others.
1832 2001
1833 .. versionchanged:: 2.6
1834 Accepts multiple input iterables.
1835
1836 .. method:: intersection_update(other, ...) 2002 .. method:: intersection_update(other, ...)
1837 set &= other & ... 2003 set &= other & ...
1838 2004
1839 Update the set, keeping only elements found in it and all others. 2005 Update the set, keeping only elements found in it and all others.
1840 2006
1841 .. versionchanged:: 2.6
1842 Accepts multiple input iterables.
1843
1844 .. method:: difference_update(other, ...) 2007 .. method:: difference_update(other, ...)
1845 set -= other | ... 2008 set -= other | ...
1846 2009
1847 Update the set, removing elements found in others. 2010 Update the set, removing elements found in others.
1848
1849 .. versionchanged:: 2.6
1850 Accepts multiple input iterables.
1851 2011
1852 .. method:: symmetric_difference_update(other) 2012 .. method:: symmetric_difference_update(other)
1853 set ^= other 2013 set ^= other
1854 2014
1855 Update the set, keeping only elements found in either set, but not in both . 2015 Update the set, keeping only elements found in either set, but not in both .
1856 2016
1857 .. method:: add(elem) 2017 .. method:: add(elem)
1858 2018
1859 Add element *elem* to the set. 2019 Add element *elem* to the set.
1860 2020
(...skipping 19 matching lines...) Expand all
1880 Note, the non-operator versions of the :meth:`update`, 2040 Note, the non-operator versions of the :meth:`update`,
1881 :meth:`intersection_update`, :meth:`difference_update`, and 2041 :meth:`intersection_update`, :meth:`difference_update`, and
1882 :meth:`symmetric_difference_update` methods will accept any iterable as an 2042 :meth:`symmetric_difference_update` methods will accept any iterable as an
1883 argument. 2043 argument.
1884 2044
1885 Note, the *elem* argument to the :meth:`__contains__`, :meth:`remove`, and 2045 Note, the *elem* argument to the :meth:`__contains__`, :meth:`remove`, and
1886 :meth:`discard` methods may be a set. To support searching for an equivalent 2046 :meth:`discard` methods may be a set. To support searching for an equivalent
1887 frozenset, the *elem* set is temporarily mutated during the search and then 2047 frozenset, the *elem* set is temporarily mutated during the search and then
1888 restored. During the search, the *elem* set should not be read or mutated 2048 restored. During the search, the *elem* set should not be read or mutated
1889 since it does not have a meaningful value. 2049 since it does not have a meaningful value.
1890
1891
1892 .. seealso::
1893
1894 :ref:`comparison-to-builtin-set`
1895 Differences between the :mod:`sets` module and the built-in set types.
1896 2050
1897 2051
1898 .. _typesmapping: 2052 .. _typesmapping:
1899 2053
1900 Mapping Types --- :class:`dict` 2054 Mapping Types --- :class:`dict`
1901 =============================== 2055 ===============================
1902 2056
1903 .. index:: 2057 .. index::
1904 object: mapping 2058 object: mapping
1905 object: dictionary 2059 object: dictionary
(...skipping 16 matching lines...) Expand all
1922 then they can be used interchangeably to index the same dictionary entry. (Note 2076 then they can be used interchangeably to index the same dictionary entry. (Note
1923 however, that since computers store floating-point numbers as approximations it 2077 however, that since computers store floating-point numbers as approximations it
1924 is usually unwise to use them as dictionary keys.) 2078 is usually unwise to use them as dictionary keys.)
1925 2079
1926 Dictionaries can be created by placing a comma-separated list of ``key: value`` 2080 Dictionaries can be created by placing a comma-separated list of ``key: value``
1927 pairs within braces, for example: ``{'jack': 4098, 'sjoerd': 4127}`` or ``{4098: 2081 pairs within braces, for example: ``{'jack': 4098, 'sjoerd': 4127}`` or ``{4098:
1928 'jack', 4127: 'sjoerd'}``, or by the :class:`dict` constructor. 2082 'jack', 4127: 'sjoerd'}``, or by the :class:`dict` constructor.
1929 2083
1930 .. class:: dict([arg]) 2084 .. class:: dict([arg])
1931 2085
1932 Return a new dictionary initialized from an optional positional argument or f rom 2086 Return a new dictionary initialized from an optional positional argument or
1933 a set of keyword arguments. If no arguments are given, return a new empty 2087 from a set of keyword arguments. If no arguments are given, return a new
1934 dictionary. If the positional argument *arg* is a mapping object, return a 2088 empty dictionary. If the positional argument *arg* is a mapping object,
1935 dictionary mapping the same keys to the same values as does the mapping objec t. 2089 return a dictionary mapping the same keys to the same values as does the
1936 Otherwise the positional argument must be a sequence, a container that suppor ts 2090 mapping object. Otherwise the positional argument must be a sequence, a
1937 iteration, or an iterator object. The elements of the argument must each als o 2091 container that supports iteration, or an iterator object. The elements of
1938 be of one of those kinds, and each must in turn contain exactly two objects. 2092 the argument must each also be of one of those kinds, and each must in turn
1939 The first is used as a key in the new dictionary, and the second as the key's 2093 contain exactly two objects. The first is used as a key in the new
1940 value. If a given key is seen more than once, the last value associated with it 2094 dictionary, and the second as the key's value. If a given key is seen more
1941 is retained in the new dictionary. 2095 than once, the last value associated with it is retained in the new
2096 dictionary.
1942 2097
1943 If keyword arguments are given, the keywords themselves with their associated 2098 If keyword arguments are given, the keywords themselves with their associated
1944 values are added as items to the dictionary. If a key is specified both in th e 2099 values are added as items to the dictionary. If a key is specified both in
1945 positional argument and as a keyword argument, the value associated with the 2100 the positional argument and as a keyword argument, the value associated with
1946 keyword is retained in the dictionary. For example, these all return a 2101 the keyword is retained in the dictionary. For example, these all return a
1947 dictionary equal to ``{"one": 1, "two": 2}``: 2102 dictionary equal to ``{"one": 1, "two": 2}``:
1948 2103
1949 * ``dict(one=1, two=2)`` 2104 * ``dict(one=1, two=2)``
1950 * ``dict({'one': 1, 'two': 2})`` 2105 * ``dict({'one': 1, 'two': 2})``
1951 * ``dict(zip(('one', 'two'), (1, 2)))`` 2106 * ``dict(zip(('one', 'two'), (1, 2)))``
1952 * ``dict([['two', 2], ['one', 1]])`` 2107 * ``dict([['two', 2], ['one', 1]])``
1953 2108
1954 The first example only works for keys that are valid Python 2109 The first example only works for keys that are valid Python identifiers; the
1955 identifiers; the others work with any valid keys. 2110 others work with any valid keys.
1956
1957 .. versionadded:: 2.2
1958
1959 .. versionchanged:: 2.3
1960 Support for building a dictionary from keyword arguments added.
1961 2111
1962 2112
1963 These are the operations that dictionaries support (and therefore, custom 2113 These are the operations that dictionaries support (and therefore, custom
1964 mapping types should support too): 2114 mapping types should support too):
1965 2115
1966 .. describe:: len(d) 2116 .. describe:: len(d)
1967 2117
1968 Return the number of items in the dictionary *d*. 2118 Return the number of items in the dictionary *d*.
1969 2119
1970 .. describe:: d[key] 2120 .. describe:: d[key]
1971 2121
1972 Return the item of *d* with key *key*. Raises a :exc:`KeyError` if *key* 2122 Return the item of *d* with key *key*. Raises a :exc:`KeyError` if *key* is
1973 is not in the map. 2123 not in the map.
1974 2124
1975 .. versionadded:: 2.5 2125 If a subclass of dict defines a method :meth:`__missing__`, if the key *ke y*
1976 If a subclass of dict defines a method :meth:`__missing__`, if the key 2126 is not present, the ``d[key]`` operation calls that method with the key *k ey*
1977 *key* is not present, the ``d[key]`` operation calls that method with 2127 as argument. The ``d[key]`` operation then returns or raises whatever is
1978 the key *key* as argument. The ``d[key]`` operation then returns or 2128 returned or raised by the ``__missing__(key)`` call if the key is not
1979 raises whatever is returned or raised by the ``__missing__(key)`` call 2129 present. No other operations or methods invoke :meth:`__missing__`. If
1980 if the key is not present. No other operations or methods invoke 2130 :meth:`__missing__` is not defined, :exc:`KeyError` is raised.
1981 :meth:`__missing__`. If :meth:`__missing__` is not defined, 2131 :meth:`__missing__` must be a method; it cannot be an instance variable::
1982 :exc:`KeyError` is raised. :meth:`__missing__` must be a method; it 2132
1983 cannot be an instance variable. For an example, see 2133 >>> class Counter(dict):
1984 :class:`collections.defaultdict`. 2134 ... def __missing__(self, key):
2135 ... return 0
2136 >>> c = Counter()
2137 >>> c['red']
2138 0
2139 >>> c['red'] += 1
2140 >>> c['red']
2141 1
2142
2143 See :class:`collections.Counter` for a complete implementation including
2144 other methods helpful for accumulating and managing tallies.
1985 2145
1986 .. describe:: d[key] = value 2146 .. describe:: d[key] = value
1987 2147
1988 Set ``d[key]`` to *value*. 2148 Set ``d[key]`` to *value*.
1989 2149
1990 .. describe:: del d[key] 2150 .. describe:: del d[key]
1991 2151
1992 Remove ``d[key]`` from *d*. Raises a :exc:`KeyError` if *key* is not in t he 2152 Remove ``d[key]`` from *d*. Raises a :exc:`KeyError` if *key* is not in t he
1993 map. 2153 map.
1994 2154
1995 .. describe:: key in d 2155 .. describe:: key in d
1996 2156
1997 Return ``True`` if *d* has a key *key*, else ``False``. 2157 Return ``True`` if *d* has a key *key*, else ``False``.
1998 2158
1999 .. versionadded:: 2.2
2000
2001 .. describe:: key not in d 2159 .. describe:: key not in d
2002 2160
2003 Equivalent to ``not key in d``. 2161 Equivalent to ``not key in d``.
2004 2162
2005 .. versionadded:: 2.2
2006
2007 .. describe:: iter(d) 2163 .. describe:: iter(d)
2008 2164
2009 Return an iterator over the keys of the dictionary. This is a shortcut 2165 Return an iterator over the keys of the dictionary. This is a shortcut
2010 for :meth:`iterkeys`. 2166 for ``iter(d.keys())``.
2011 2167
2012 .. method:: clear() 2168 .. method:: clear()
2013 2169
2014 Remove all items from the dictionary. 2170 Remove all items from the dictionary.
2015 2171
2016 .. method:: copy() 2172 .. method:: copy()
2017 2173
2018 Return a shallow copy of the dictionary. 2174 Return a shallow copy of the dictionary.
2019 2175
2020 .. method:: fromkeys(seq[, value]) 2176 .. classmethod:: fromkeys(seq[, value])
2021 2177
2022 Create a new dictionary with keys from *seq* and values set to *value*. 2178 Create a new dictionary with keys from *seq* and values set to *value*.
2023 2179
2024 :func:`fromkeys` is a class method that returns a new dictionary. *value* 2180 :meth:`fromkeys` is a class method that returns a new dictionary. *value*
2025 defaults to ``None``. 2181 defaults to ``None``.
2026
2027 .. versionadded:: 2.3
2028 2182
2029 .. method:: get(key[, default]) 2183 .. method:: get(key[, default])
2030 2184
2031 Return the value for *key* if *key* is in the dictionary, else *default*. 2185 Return the value for *key* if *key* is in the dictionary, else *default*.
2032 If *default* is not given, it defaults to ``None``, so that this method 2186 If *default* is not given, it defaults to ``None``, so that this method
2033 never raises a :exc:`KeyError`. 2187 never raises a :exc:`KeyError`.
2034 2188
2035 .. method:: has_key(key)
2036
2037 Test for the presence of *key* in the dictionary. :meth:`has_key` is
2038 deprecated in favor of ``key in d``.
2039
2040 .. method:: items() 2189 .. method:: items()
2041 2190
2042 Return a copy of the dictionary's list of ``(key, value)`` pairs. 2191 Return a new view of the dictionary's items (``(key, value)`` pairs). See
2043 2192 below for documentation of view objects.
2044 .. impl-detail::
2045
2046 Keys and values are listed in an arbitrary order which is non-random,
2047 varies across Python implementations, and depends on the dictionary's
2048 history of insertions and deletions.
2049
2050 If :meth:`items`, :meth:`keys`, :meth:`values`, :meth:`iteritems`,
2051 :meth:`iterkeys`, and :meth:`itervalues` are called with no intervening
2052 modifications to the dictionary, the lists will directly correspond. This
2053 allows the creation of ``(value, key)`` pairs using :func:`zip`: ``pairs =
2054 zip(d.values(), d.keys())``. The same relationship holds for the
2055 :meth:`iterkeys` and :meth:`itervalues` methods: ``pairs =
2056 zip(d.itervalues(), d.iterkeys())`` provides the same value for
2057 ``pairs``. Another way to create the same list is ``pairs = [(v, k) for
2058 (k, v) in d.iteritems()]``.
2059
2060 .. method:: iteritems()
2061
2062 Return an iterator over the dictionary's ``(key, value)`` pairs. See the
2063 note for :meth:`dict.items`.
2064
2065 Using :meth:`iteritems` while adding or deleting entries in the dictionary
2066 may raise a :exc:`RuntimeError` or fail to iterate over all entries.
2067
2068 .. versionadded:: 2.2
2069
2070 .. method:: iterkeys()
2071
2072 Return an iterator over the dictionary's keys. See the note for
2073 :meth:`dict.items`.
2074
2075 Using :meth:`iterkeys` while adding or deleting entries in the dictionary
2076 may raise a :exc:`RuntimeError` or fail to iterate over all entries.
2077
2078 .. versionadded:: 2.2
2079
2080 .. method:: itervalues()
2081
2082 Return an iterator over the dictionary's values. See the note for
2083 :meth:`dict.items`.
2084
2085 Using :meth:`itervalues` while adding or deleting entries in the
2086 dictionary may raise a :exc:`RuntimeError` or fail to iterate over all
2087 entries.
2088
2089 .. versionadded:: 2.2
2090 2193
2091 .. method:: keys() 2194 .. method:: keys()
2092 2195
2093 Return a copy of the dictionary's list of keys. See the note for 2196 Return a new view of the dictionary's keys. See below for documentation o f
2094 :meth:`dict.items`. 2197 view objects.
2095 2198
2096 .. method:: pop(key[, default]) 2199 .. method:: pop(key[, default])
2097 2200
2098 If *key* is in the dictionary, remove it and return its value, else return 2201 If *key* is in the dictionary, remove it and return its value, else return
2099 *default*. If *default* is not given and *key* is not in the dictionary, 2202 *default*. If *default* is not given and *key* is not in the dictionary,
2100 a :exc:`KeyError` is raised. 2203 a :exc:`KeyError` is raised.
2101 2204
2102 .. versionadded:: 2.3
2103
2104 .. method:: popitem() 2205 .. method:: popitem()
2105 2206
2106 Remove and return an arbitrary ``(key, value)`` pair from the dictionary. 2207 Remove and return an arbitrary ``(key, value)`` pair from the dictionary.
2107 2208
2108 :func:`popitem` is useful to destructively iterate over a dictionary, as 2209 :meth:`popitem` is useful to destructively iterate over a dictionary, as
2109 often used in set algorithms. If the dictionary is empty, calling 2210 often used in set algorithms. If the dictionary is empty, calling
2110 :func:`popitem` raises a :exc:`KeyError`. 2211 :meth:`popitem` raises a :exc:`KeyError`.
2111 2212
2112 .. method:: setdefault(key[, default]) 2213 .. method:: setdefault(key[, default])
2113 2214
2114 If *key* is in the dictionary, return its value. If not, insert *key* 2215 If *key* is in the dictionary, return its value. If not, insert *key*
2115 with a value of *default* and return *default*. *default* defaults to 2216 with a value of *default* and return *default*. *default* defaults to
2116 ``None``. 2217 ``None``.
2117 2218
2118 .. method:: update([other]) 2219 .. method:: update([other])
2119 2220
2120 Update the dictionary with the key/value pairs from *other*, overwriting 2221 Update the dictionary with the key/value pairs from *other*, overwriting
2121 existing keys. Return ``None``. 2222 existing keys. Return ``None``.
2122 2223
2123 :func:`update` accepts either another dictionary object or an iterable of 2224 :meth:`update` accepts either another dictionary object or an iterable of
2124 key/value pairs (as tuples or other iterables of length two). If keyword 2225 key/value pairs (as tuples or other iterables of length two). If keyword
2125 arguments are specified, the dictionary is then updated with those 2226 arguments are specified, the dictionary is then updated with those
2126 key/value pairs: ``d.update(red=1, blue=2)``. 2227 key/value pairs: ``d.update(red=1, blue=2)``.
2127 2228
2128 .. versionchanged:: 2.4
2129 Allowed the argument to be an iterable of key/value pairs and allowed
2130 keyword arguments.
2131
2132 .. method:: values() 2229 .. method:: values()
2133
2134 Return a copy of the dictionary's list of values. See the note for
2135 :meth:`dict.items`.
2136
2137 .. method:: viewitems()
2138
2139 Return a new view of the dictionary's items (``(key, value)`` pairs). See
2140 below for documentation of view objects.
2141
2142 .. versionadded:: 2.7
2143
2144 .. method:: viewkeys()
2145
2146 Return a new view of the dictionary's keys. See below for documentation o f
2147 view objects.
2148
2149 .. versionadded:: 2.7
2150
2151 .. method:: viewvalues()
2152 2230
2153 Return a new view of the dictionary's values. See below for documentation of 2231 Return a new view of the dictionary's values. See below for documentation of
2154 view objects. 2232 view objects.
2155 2233
2156 .. versionadded:: 2.7
2157
2158 2234
2159 .. _dict-views: 2235 .. _dict-views:
2160 2236
2161 Dictionary view objects 2237 Dictionary view objects
2162 ----------------------- 2238 -----------------------
2163 2239
2164 The objects returned by :meth:`dict.viewkeys`, :meth:`dict.viewvalues` and 2240 The objects returned by :meth:`dict.keys`, :meth:`dict.values` and
2165 :meth:`dict.viewitems` are *view objects*. They provide a dynamic view on the 2241 :meth:`dict.items` are *view objects*. They provide a dynamic view on the
2166 dictionary's entries, which means that when the dictionary changes, the view 2242 dictionary's entries, which means that when the dictionary changes, the view
2167 reflects these changes. 2243 reflects these changes.
2168 2244
2169 Dictionary views can be iterated over to yield their respective data, and 2245 Dictionary views can be iterated over to yield their respective data, and
2170 support membership tests: 2246 support membership tests:
2171 2247
2172 .. describe:: len(dictview) 2248 .. describe:: len(dictview)
2173 2249
2174 Return the number of entries in the dictionary. 2250 Return the number of entries in the dictionary.
2175 2251
(...skipping 13 matching lines...) Expand all
2189 Iterating views while adding or deleting entries in the dictionary may raise 2265 Iterating views while adding or deleting entries in the dictionary may raise
2190 a :exc:`RuntimeError` or fail to iterate over all entries. 2266 a :exc:`RuntimeError` or fail to iterate over all entries.
2191 2267
2192 .. describe:: x in dictview 2268 .. describe:: x in dictview
2193 2269
2194 Return ``True`` if *x* is in the underlying dictionary's keys, values or 2270 Return ``True`` if *x* is in the underlying dictionary's keys, values or
2195 items (in the latter case, *x* should be a ``(key, value)`` tuple). 2271 items (in the latter case, *x* should be a ``(key, value)`` tuple).
2196 2272
2197 2273
2198 Keys views are set-like since their entries are unique and hashable. If all 2274 Keys views are set-like since their entries are unique and hashable. If all
2199 values are hashable, so that (key, value) pairs are unique and hashable, then 2275 values are hashable, so that ``(key, value)`` pairs are unique and hashable,
2200 the items view is also set-like. (Values views are not treated as set-like 2276 then the items view is also set-like. (Values views are not treated as set-like
2201 since the entries are generally not unique.) Then these set operations are 2277 since the entries are generally not unique.) For set-like views, all of the
2202 available ("other" refers either to another view or a set): 2278 operations defined for the abstract base class :class:`collections.Set` are
2203 2279 available (for example, ``==``, ``<``, or ``^``).
2204 .. describe:: dictview & other
2205
2206 Return the intersection of the dictview and the other object as a new set.
2207
2208 .. describe:: dictview | other
2209
2210 Return the union of the dictview and the other object as a new set.
2211
2212 .. describe:: dictview - other
2213
2214 Return the difference between the dictview and the other object (all elements
2215 in *dictview* that aren't in *other*) as a new set.
2216
2217 .. describe:: dictview ^ other
2218
2219 Return the symmetric difference (all elements either in *dictview* or
2220 *other*, but not in both) of the dictview and the other object as a new set.
2221
2222 2280
2223 An example of dictionary view usage:: 2281 An example of dictionary view usage::
2224 2282
2225 >>> dishes = {'eggs': 2, 'sausage': 1, 'bacon': 1, 'spam': 500} 2283 >>> dishes = {'eggs': 2, 'sausage': 1, 'bacon': 1, 'spam': 500}
2226 >>> keys = dishes.viewkeys() 2284 >>> keys = dishes.keys()
2227 >>> values = dishes.viewvalues() 2285 >>> values = dishes.values()
2228 2286
2229 >>> # iteration 2287 >>> # iteration
2230 >>> n = 0 2288 >>> n = 0
2231 >>> for val in values: 2289 >>> for val in values:
2232 ... n += val 2290 ... n += val
2233 >>> print(n) 2291 >>> print(n)
2234 504 2292 504
2235 2293
2236 >>> # keys and values are iterated over in the same order 2294 >>> # keys and values are iterated over in the same order
2237 >>> list(keys) 2295 >>> list(keys)
2238 ['eggs', 'bacon', 'sausage', 'spam'] 2296 ['eggs', 'bacon', 'sausage', 'spam']
2239 >>> list(values) 2297 >>> list(values)
2240 [2, 1, 1, 500] 2298 [2, 1, 1, 500]
2241 2299
2242 >>> # view objects are dynamic and reflect dict changes 2300 >>> # view objects are dynamic and reflect dict changes
2243 >>> del dishes['eggs'] 2301 >>> del dishes['eggs']
2244 >>> del dishes['sausage'] 2302 >>> del dishes['sausage']
2245 >>> list(keys) 2303 >>> list(keys)
2246 ['spam', 'bacon'] 2304 ['spam', 'bacon']
2247 2305
2248 >>> # set operations 2306 >>> # set operations
2249 >>> keys & {'eggs', 'bacon', 'salad'} 2307 >>> keys & {'eggs', 'bacon', 'salad'}
2250 {'bacon'} 2308 {'bacon'}
2251 2309 >>> keys ^ {'sausage', 'juice'}
2252 2310 {'juice', 'eggs', 'bacon', 'spam'}
2253 .. _bltin-file-objects:
2254
2255 File Objects
2256 ============
2257
2258 .. index::
2259 object: file
2260 builtin: file
2261 module: os
2262 module: socket
2263
2264 File objects are implemented using C's ``stdio`` package and can be
2265 created with the built-in :func:`open` function. File
2266 objects are also returned by some other built-in functions and methods,
2267 such as :func:`os.popen` and :func:`os.fdopen` and the :meth:`makefile`
2268 method of socket objects. Temporary files can be created using the
2269 :mod:`tempfile` module, and high-level file operations such as copying,
2270 moving, and deleting files and directories can be achieved with the
2271 :mod:`shutil` module.
2272
2273 When a file operation fails for an I/O-related reason, the exception
2274 :exc:`IOError` is raised. This includes situations where the operation is not
2275 defined for some reason, like :meth:`seek` on a tty device or writing a file
2276 opened for reading.
2277
2278 Files have the following methods:
2279
2280
2281 .. method:: file.close()
2282
2283 Close the file. A closed file cannot be read or written any more. Any operat ion
2284 which requires that the file be open will raise a :exc:`ValueError` after the
2285 file has been closed. Calling :meth:`close` more than once is allowed.
2286
2287 As of Python 2.5, you can avoid having to call this method explicitly if you use
2288 the :keyword:`with` statement. For example, the following code will
2289 automatically close *f* when the :keyword:`with` block is exited::
2290
2291 from __future__ import with_statement # This isn't required in Python 2.6
2292
2293 with open("hello.txt") as f:
2294 for line in f:
2295 print line
2296
2297 In older versions of Python, you would have needed to do this to get the same
2298 effect::
2299
2300 f = open("hello.txt")
2301 try:
2302 for line in f:
2303 print line
2304 finally:
2305 f.close()
2306
2307 .. note::
2308
2309 Not all "file-like" types in Python support use as a context manager for t he
2310 :keyword:`with` statement. If your code is intended to work with any file -like
2311 object, you can use the function :func:`contextlib.closing` instead of usi ng
2312 the object directly.
2313
2314
2315 .. method:: file.flush()
2316
2317 Flush the internal buffer, like ``stdio``'s :cfunc:`fflush`. This may be a
2318 no-op on some file-like objects.
2319
2320 .. note::
2321
2322 :meth:`flush` does not necessarily write the file's data to disk. Use
2323 :meth:`flush` followed by :func:`os.fsync` to ensure this behavior.
2324
2325
2326 .. method:: file.fileno()
2327
2328 .. index::
2329 pair: file; descriptor
2330 module: fcntl
2331
2332 Return the integer "file descriptor" that is used by the underlying
2333 implementation to request I/O operations from the operating system. This can be
2334 useful for other, lower level interfaces that use file descriptors, such as t he
2335 :mod:`fcntl` module or :func:`os.read` and friends.
2336
2337 .. note::
2338
2339 File-like objects which do not have a real file descriptor should *not* pr ovide
2340 this method!
2341
2342
2343 .. method:: file.isatty()
2344
2345 Return ``True`` if the file is connected to a tty(-like) device, else ``False ``.
2346
2347 .. note::
2348
2349 If a file-like object is not associated with a real file, this method shou ld
2350 *not* be implemented.
2351
2352
2353 .. method:: file.next()
2354
2355 A file object is its own iterator, for example ``iter(f)`` returns *f* (unles s
2356 *f* is closed). When a file is used as an iterator, typically in a
2357 :keyword:`for` loop (for example, ``for line in f: print line``), the
2358 :meth:`.next` method is called repeatedly. This method returns the next inpu t
2359 line, or raises :exc:`StopIteration` when EOF is hit when the file is open fo r
2360 reading (behavior is undefined when the file is open for writing). In order to
2361 make a :keyword:`for` loop the most efficient way of looping over the lines o f a
2362 file (a very common operation), the :meth:`next` method uses a hidden read-ah ead
2363 buffer. As a consequence of using a read-ahead buffer, combining :meth:`.nex t`
2364 with other file methods (like :meth:`readline`) does not work right. However ,
2365 using :meth:`seek` to reposition the file to an absolute position will flush the
2366 read-ahead buffer.
2367
2368 .. versionadded:: 2.3
2369
2370
2371 .. method:: file.read([size])
2372
2373 Read at most *size* bytes from the file (less if the read hits EOF before
2374 obtaining *size* bytes). If the *size* argument is negative or omitted, read
2375 all data until EOF is reached. The bytes are returned as a string object. A n
2376 empty string is returned when EOF is encountered immediately. (For certain
2377 files, like ttys, it makes sense to continue reading after an EOF is hit.) N ote
2378 that this method may call the underlying C function :cfunc:`fread` more than
2379 once in an effort to acquire as close to *size* bytes as possible. Also note
2380 that when in non-blocking mode, less data than was requested may be
2381 returned, even if no *size* parameter was given.
2382
2383 .. note::
2384 This function is simply a wrapper for the underlying
2385 :cfunc:`fread` C function, and will behave the same in corner cases,
2386 such as whether the EOF value is cached.
2387
2388
2389 .. method:: file.readline([size])
2390
2391 Read one entire line from the file. A trailing newline character is kept in the
2392 string (but may be absent when a file ends with an incomplete line). [#]_ If
2393 the *size* argument is present and non-negative, it is a maximum byte count
2394 (including the trailing newline) and an incomplete line may be returned. An
2395 empty string is returned *only* when EOF is encountered immediately.
2396
2397 .. note::
2398
2399 Unlike ``stdio``'s :cfunc:`fgets`, the returned string contains null chara cters
2400 (``'\0'``) if they occurred in the input.
2401
2402
2403 .. method:: file.readlines([sizehint])
2404
2405 Read until EOF using :meth:`readline` and return a list containing the lines
2406 thus read. If the optional *sizehint* argument is present, instead of
2407 reading up to EOF, whole lines totalling approximately *sizehint* bytes
2408 (possibly after rounding up to an internal buffer size) are read. Objects
2409 implementing a file-like interface may choose to ignore *sizehint* if it
2410 cannot be implemented, or cannot be implemented efficiently.
2411
2412
2413 .. method:: file.xreadlines()
2414
2415 This method returns the same thing as ``iter(f)``.
2416
2417 .. versionadded:: 2.1
2418
2419 .. deprecated:: 2.3
2420 Use ``for line in file`` instead.
2421
2422
2423 .. method:: file.seek(offset[, whence])
2424
2425 Set the file's current position, like ``stdio``'s :cfunc:`fseek`. The *whence *
2426 argument is optional and defaults to ``os.SEEK_SET`` or ``0`` (absolute file
2427 positioning); other values are ``os.SEEK_CUR`` or ``1`` (seek relative to the
2428 current position) and ``os.SEEK_END`` or ``2`` (seek relative to the file's
2429 end). There is no return value.
2430
2431 For example, ``f.seek(2, os.SEEK_CUR)`` advances the position by two and
2432 ``f.seek(-3, os.SEEK_END)`` sets the position to the third to last.
2433
2434 Note that if the file is opened for appending
2435 (mode ``'a'`` or ``'a+'``), any :meth:`seek` operations will be undone at the
2436 next write. If the file is only opened for writing in append mode (mode
2437 ``'a'``), this method is essentially a no-op, but it remains useful for files
2438 opened in append mode with reading enabled (mode ``'a+'``). If the file is
2439 opened in text mode (without ``'b'``), only offsets returned by :meth:`tell` are
2440 legal. Use of other offsets causes undefined behavior.
2441
2442 Note that not all file objects are seekable.
2443
2444 .. versionchanged:: 2.6
2445 Passing float values as offset has been deprecated.
2446
2447
2448 .. method:: file.tell()
2449
2450 Return the file's current position, like ``stdio``'s :cfunc:`ftell`.
2451
2452 .. note::
2453
2454 On Windows, :meth:`tell` can return illegal values (after an :cfunc:`fgets `)
2455 when reading files with Unix-style line-endings. Use binary mode (``'rb'`` ) to
2456 circumvent this problem.
2457
2458
2459 .. method:: file.truncate([size])
2460
2461 Truncate the file's size. If the optional *size* argument is present, the fi le
2462 is truncated to (at most) that size. The size defaults to the current positi on.
2463 The current file position is not changed. Note that if a specified size exce eds
2464 the file's current size, the result is platform-dependent: possibilities
2465 include that the file may remain unchanged, increase to the specified size as if
2466 zero-filled, or increase to the specified size with undefined new content.
2467 Availability: Windows, many Unix variants.
2468
2469
2470 .. method:: file.write(str)
2471
2472 Write a string to the file. There is no return value. Due to buffering, the
2473 string may not actually show up in the file until the :meth:`flush` or
2474 :meth:`close` method is called.
2475
2476
2477 .. method:: file.writelines(sequence)
2478
2479 Write a sequence of strings to the file. The sequence can be any iterable
2480 object producing strings, typically a list of strings. There is no return val ue.
2481 (The name is intended to match :meth:`readlines`; :meth:`writelines` does not
2482 add line separators.)
2483
2484 Files support the iterator protocol. Each iteration returns the same result as
2485 ``file.readline()``, and iteration ends when the :meth:`readline` method returns
2486 an empty string.
2487
2488 File objects also offer a number of other interesting attributes. These are not
2489 required for file-like objects, but should be implemented if they make sense for
2490 the particular object.
2491
2492
2493 .. attribute:: file.closed
2494
2495 bool indicating the current state of the file object. This is a read-only
2496 attribute; the :meth:`close` method changes the value. It may not be availabl e
2497 on all file-like objects.
2498
2499
2500 .. attribute:: file.encoding
2501
2502 The encoding that this file uses. When Unicode strings are written to a file,
2503 they will be converted to byte strings using this encoding. In addition, when
2504 the file is connected to a terminal, the attribute gives the encoding that th e
2505 terminal is likely to use (that information might be incorrect if the user h as
2506 misconfigured the terminal). The attribute is read-only and may not be prese nt
2507 on all file-like objects. It may also be ``None``, in which case the file use s
2508 the system default encoding for converting Unicode strings.
2509
2510 .. versionadded:: 2.3
2511
2512
2513 .. attribute:: file.errors
2514
2515 The Unicode error handler used along with the encoding.
2516
2517 .. versionadded:: 2.6
2518
2519
2520 .. attribute:: file.mode
2521
2522 The I/O mode for the file. If the file was created using the :func:`open`
2523 built-in function, this will be the value of the *mode* parameter. This is a
2524 read-only attribute and may not be present on all file-like objects.
2525
2526
2527 .. attribute:: file.name
2528
2529 If the file object was created using :func:`open`, the name of the file.
2530 Otherwise, some string that indicates the source of the file object, of the
2531 form ``<...>``. This is a read-only attribute and may not be present on all
2532 file-like objects.
2533
2534
2535 .. attribute:: file.newlines
2536
2537 If Python was built with the :option:`--with-universal-newlines` option to
2538 :program:`configure` (the default) this read-only attribute exists, and for
2539 files opened in universal newline read mode it keeps track of the types of
2540 newlines encountered while reading the file. The values it can take are
2541 ``'\r'``, ``'\n'``, ``'\r\n'``, ``None`` (unknown, no newlines read yet) or a
2542 tuple containing all the newline types seen, to indicate that multiple newlin e
2543 conventions were encountered. For files not opened in universal newline read
2544 mode the value of this attribute will be ``None``.
2545
2546
2547 .. attribute:: file.softspace
2548
2549 Boolean that indicates whether a space character needs to be printed before
2550 another value when using the :keyword:`print` statement. Classes that are try ing
2551 to simulate a file object should also have a writable :attr:`softspace`
2552 attribute, which should be initialized to zero. This will be automatic for m ost
2553 classes implemented in Python (care may be needed for objects that override
2554 attribute access); types implemented in C will have to provide a writable
2555 :attr:`softspace` attribute.
2556
2557 .. note::
2558
2559 This attribute is not used to control the :keyword:`print` statement, but to
2560 allow the implementation of :keyword:`print` to keep track of its internal
2561 state.
2562 2311
2563 2312
2564 .. _typememoryview: 2313 .. _typememoryview:
2565 2314
2566 memoryview type 2315 memoryview type
2567 =============== 2316 ===============
2568 2317
2569 .. versionadded:: 2.7
2570
2571 :class:`memoryview` objects allow Python code to access the internal data 2318 :class:`memoryview` objects allow Python code to access the internal data
2572 of an object that supports the buffer protocol without copying. Memory 2319 of an object that supports the :ref:`buffer protocol <bufferobjects>` without
2573 is generally interpreted as simple bytes. 2320 copying. Memory is generally interpreted as simple bytes.
2574 2321
2575 .. class:: memoryview(obj) 2322 .. class:: memoryview(obj)
2576 2323
2577 Create a :class:`memoryview` that references *obj*, which must support the 2324 Create a :class:`memoryview` that references *obj*, which must support the
2578 buffer protocol. Builtin objects that support the buffer protocol include 2325 buffer protocol. Builtin objects that support the buffer protocol include
2579 :class:`str` and :class:`bytearray` (but not :class:`unicode`). 2326 :class:`bytes` and :class:`bytearray`.
2580 2327
2581 A :class:`memoryview` has the notion of an *element*, which is the 2328 A :class:`memoryview` has the notion of an *element*, which is the
2582 atomic memory unit handled by the originating object *obj*. For many 2329 atomic memory unit handled by the originating object *obj*. For many
2583 simple types such as :class:`str` and :class:`bytearray`, an element 2330 simple types such as :class:`bytes` and :class:`bytearray`, an element
2584 is a single byte, but other third-party types may expose larger elements. 2331 is a single byte, but other types such as :class:`array.array` may have
2332 bigger elements.
2585 2333
2586 ``len(view)`` returns the total number of elements in the memoryview, 2334 ``len(view)`` returns the total number of elements in the memoryview,
2587 *view*. The :class:`~memoryview.itemsize` attribute will give you the 2335 *view*. The :class:`~memoryview.itemsize` attribute will give you the
2588 number of bytes in a single element. 2336 number of bytes in a single element.
2589 2337
2590 A :class:`memoryview` supports slicing to expose its data. Taking a single 2338 A :class:`memoryview` supports slicing to expose its data. Taking a single
2591 index will return a single element as a :class:`str` object. Full 2339 index will return a single element as a :class:`bytes` object. Full
2592 slicing will result in a subview:: 2340 slicing will result in a subview::
2593 2341
2594 >>> v = memoryview('abcefg') 2342 >>> v = memoryview(b'abcefg')
2595 >>> v[1] 2343 >>> v[1]
2596 'b' 2344 b'b'
2597 >>> v[-1] 2345 >>> v[-1]
2598 'g' 2346 b'g'
2599 >>> v[1:4] 2347 >>> v[1:4]
2600 <memory at 0x77ab28> 2348 <memory at 0x77ab28>
2601 >>> v[1:4].tobytes() 2349 >>> bytes(v[1:4])
2602 'bce' 2350 b'bce'
2603 2351
2604 If the object the memoryview is over supports changing its data, the 2352 If the object the memoryview is over supports changing its data, the
2605 memoryview supports slice assignment:: 2353 memoryview supports slice assignment::
2606 2354
2607 >>> data = bytearray('abcefg') 2355 >>> data = bytearray(b'abcefg')
2608 >>> v = memoryview(data) 2356 >>> v = memoryview(data)
2609 >>> v.readonly 2357 >>> v.readonly
2610 False 2358 False
2611 >>> v[0] = 'z' 2359 >>> v[0] = b'z'
2612 >>> data 2360 >>> data
2613 bytearray(b'zbcefg') 2361 bytearray(b'zbcefg')
2614 >>> v[1:4] = '123' 2362 >>> v[1:4] = b'123'
2615 >>> data 2363 >>> data
2616 bytearray(b'z123fg') 2364 bytearray(b'a123fg')
2617 >>> v[2] = 'spam' 2365 >>> v[2] = b'spam'
2618 Traceback (most recent call last): 2366 Traceback (most recent call last):
2619 File "<stdin>", line 1, in <module> 2367 File "<stdin>", line 1, in <module>
2620 ValueError: cannot modify size of memoryview object 2368 ValueError: cannot modify size of memoryview object
2621 2369
2622 Notice how the size of the memoryview object cannot be changed. 2370 Notice how the size of the memoryview object cannot be changed.
2623 2371
2624 :class:`memoryview` has two methods: 2372 :class:`memoryview` has several methods:
2625 2373
2626 .. method:: tobytes() 2374 .. method:: tobytes()
2627 2375
2628 Return the data in the buffer as a bytestring (an object of class 2376 Return the data in the buffer as a bytestring. This is equivalent to
2629 :class:`str`). :: 2377 calling the :class:`bytes` constructor on the memoryview. ::
2630 2378
2631 >>> m = memoryview("abc") 2379 >>> m = memoryview(b"abc")
2632 >>> m.tobytes() 2380 >>> m.tobytes()
2633 'abc' 2381 b'abc'
2382 >>> bytes(m)
2383 b'abc'
2634 2384
2635 .. method:: tolist() 2385 .. method:: tolist()
2636 2386
2637 Return the data in the buffer as a list of integers. :: 2387 Return the data in the buffer as a list of integers. ::
2638 2388
2639 >>> memoryview("abc").tolist() 2389 >>> memoryview(b'abc').tolist()
2640 [97, 98, 99] 2390 [97, 98, 99]
2391
2392 .. method:: release()
2393
2394 Release the underlying buffer exposed by the memoryview object. Many
2395 objects take special actions when a view is held on them (for example,
2396 a :class:`bytearray` would temporarily forbid resizing); therefore,
2397 calling release() is handy to remove these restrictions (and free any
2398 dangling resources) as soon as possible.
2399
2400 After this method has been called, any further operation on the view
2401 raises a :class:`ValueError` (except :meth:`release()` itself which can
2402 be called multiple times)::
2403
2404 >>> m = memoryview(b'abc')
2405 >>> m.release()
2406 >>> m[0]
2407 Traceback (most recent call last):
2408 File "<stdin>", line 1, in <module>
2409 ValueError: operation forbidden on released memoryview object
2410
2411 The context management protocol can be used for a similar effect,
2412 using the ``with`` statement::
2413
2414 >>> with memoryview(b'abc') as m:
2415 ... m[0]
2416 ...
2417 b'a'
2418 >>> m[0]
2419 Traceback (most recent call last):
2420 File "<stdin>", line 1, in <module>
2421 ValueError: operation forbidden on released memoryview object
2422
2423 .. versionadded:: 3.2
2641 2424
2642 There are also several readonly attributes available: 2425 There are also several readonly attributes available:
2643 2426
2644 .. attribute:: format 2427 .. attribute:: format
2645 2428
2646 A string containing the format (in :mod:`struct` module style) for each 2429 A string containing the format (in :mod:`struct` module style) for each
2647 element in the view. This defaults to ``'B'``, a simple bytestring. 2430 element in the view. This defaults to ``'B'``, a simple bytestring.
2648 2431
2649 .. attribute:: itemsize 2432 .. attribute:: itemsize
2650 2433
2651 The size in bytes of each element of the memoryview. 2434 The size in bytes of each element of the memoryview::
2435
2436 >>> m = memoryview(array.array('H', [1,2,3]))
2437 >>> m.itemsize
2438 2
2439 >>> m[0]
2440 b'\x01\x00'
2441 >>> len(m[0]) == m.itemsize
2442 True
2652 2443
2653 .. attribute:: shape 2444 .. attribute:: shape
2654 2445
2655 A tuple of integers the length of :attr:`ndim` giving the shape of the 2446 A tuple of integers the length of :attr:`ndim` giving the shape of the
2656 memory as a N-dimensional array. 2447 memory as a N-dimensional array.
2657 2448
2658 .. attribute:: ndim 2449 .. attribute:: ndim
2659 2450
2660 An integer indicating how many dimensions of a multi-dimensional array the 2451 An integer indicating how many dimensions of a multi-dimensional array the
2661 memory represents. 2452 memory represents.
2662 2453
2663 .. attribute:: strides 2454 .. attribute:: strides
2664 2455
2665 A tuple of integers the length of :attr:`ndim` giving the size in bytes to 2456 A tuple of integers the length of :attr:`ndim` giving the size in bytes to
2666 access each element for each dimension of the array. 2457 access each element for each dimension of the array.
2667 2458
2668 .. attribute:: readonly 2459 .. attribute:: readonly
2669 2460
2670 A bool indicating whether the memory is read only. 2461 A bool indicating whether the memory is read only.
2671 2462
2672 .. memoryview.suboffsets isn't documented because it only seems useful for C 2463 .. memoryview.suboffsets isn't documented because it only seems useful for C
2673 2464
2674 2465
2675 .. _typecontextmanager: 2466 .. _typecontextmanager:
2676 2467
2677 Context Manager Types 2468 Context Manager Types
2678 ===================== 2469 =====================
2679
2680 .. versionadded:: 2.5
2681 2470
2682 .. index:: 2471 .. index::
2683 single: context manager 2472 single: context manager
2684 single: context management protocol 2473 single: context management protocol
2685 single: protocol; context management 2474 single: protocol; context management
2686 2475
2687 Python's :keyword:`with` statement supports the concept of a runtime context 2476 Python's :keyword:`with` statement supports the concept of a runtime context
2688 defined by a context manager. This is implemented using two separate methods 2477 defined by a context manager. This is implemented using a pair of methods
2689 that allow user-defined classes to define a runtime context that is entered 2478 that allow user-defined classes to define a runtime context that is entered
2690 before the statement body is executed and exited when the statement ends. 2479 before the statement body is executed and exited when the statement ends:
2691
2692 The :dfn:`context management protocol` consists of a pair of methods that need
2693 to be provided for a context manager object to define a runtime context:
2694 2480
2695 2481
2696 .. method:: contextmanager.__enter__() 2482 .. method:: contextmanager.__enter__()
2697 2483
2698 Enter the runtime context and return either this object or another object 2484 Enter the runtime context and return either this object or another object
2699 related to the runtime context. The value returned by this method is bound to 2485 related to the runtime context. The value returned by this method is bound to
2700 the identifier in the :keyword:`as` clause of :keyword:`with` statements usin g 2486 the identifier in the :keyword:`as` clause of :keyword:`with` statements usin g
2701 this context manager. 2487 this context manager.
2702 2488
2703 An example of a context manager that returns itself is a file object. File 2489 An example of a context manager that returns itself is a :term:`file object`.
2704 objects return themselves from __enter__() to allow :func:`open` to be used a s 2490 File objects return themselves from __enter__() to allow :func:`open` to be
2705 the context expression in a :keyword:`with` statement. 2491 used as the context expression in a :keyword:`with` statement.
2706 2492
2707 An example of a context manager that returns a related object is the one 2493 An example of a context manager that returns a related object is the one
2708 returned by :func:`decimal.localcontext`. These managers set the active 2494 returned by :func:`decimal.localcontext`. These managers set the active
2709 decimal context to a copy of the original decimal context and then return the 2495 decimal context to a copy of the original decimal context and then return the
2710 copy. This allows changes to be made to the current decimal context in the bo dy 2496 copy. This allows changes to be made to the current decimal context in the bo dy
2711 of the :keyword:`with` statement without affecting code outside the 2497 of the :keyword:`with` statement without affecting code outside the
2712 :keyword:`with` statement. 2498 :keyword:`with` statement.
2713 2499
2714 2500
2715 .. method:: contextmanager.__exit__(exc_type, exc_val, exc_tb) 2501 .. method:: contextmanager.__exit__(exc_type, exc_val, exc_tb)
(...skipping 15 matching lines...) Expand all
2731 successfully and does not want to suppress the raised exception. This allows 2517 successfully and does not want to suppress the raised exception. This allows
2732 context management code (such as ``contextlib.nested``) to easily detect whet her 2518 context management code (such as ``contextlib.nested``) to easily detect whet her
2733 or not an :meth:`__exit__` method has actually failed. 2519 or not an :meth:`__exit__` method has actually failed.
2734 2520
2735 Python defines several context managers to support easy thread synchronisation, 2521 Python defines several context managers to support easy thread synchronisation,
2736 prompt closure of files or other objects, and simpler manipulation of the active 2522 prompt closure of files or other objects, and simpler manipulation of the active
2737 decimal arithmetic context. The specific types are not treated specially beyond 2523 decimal arithmetic context. The specific types are not treated specially beyond
2738 their implementation of the context management protocol. See the 2524 their implementation of the context management protocol. See the
2739 :mod:`contextlib` module for some examples. 2525 :mod:`contextlib` module for some examples.
2740 2526
2741 Python's :term:`generator`\s and the ``contextlib.contextmanager`` :term:`decora tor` 2527 Python's :term:`generator`\s and the :class:`contextlib.contextmanager` decorato r
2742 provide a convenient way to implement these protocols. If a generator function is 2528 provide a convenient way to implement these protocols. If a generator function is
2743 decorated with the ``contextlib.contextmanager`` decorator, it will return a 2529 decorated with the :class:`contextlib.contextmanager` decorator, it will return a
2744 context manager implementing the necessary :meth:`__enter__` and 2530 context manager implementing the necessary :meth:`__enter__` and
2745 :meth:`__exit__` methods, rather than the iterator produced by an undecorated 2531 :meth:`__exit__` methods, rather than the iterator produced by an undecorated
2746 generator function. 2532 generator function.
2747 2533
2748 Note that there is no specific slot for any of these methods in the type 2534 Note that there is no specific slot for any of these methods in the type
2749 structure for Python objects in the Python/C API. Extension types wanting to 2535 structure for Python objects in the Python/C API. Extension types wanting to
2750 define these methods must provide them as a normal Python accessible method. 2536 define these methods must provide them as a normal Python accessible method.
2751 Compared to the overhead of setting up the runtime context, the overhead of a 2537 Compared to the overhead of setting up the runtime context, the overhead of a
2752 single class dictionary lookup is negligible. 2538 single class dictionary lookup is negligible.
2753 2539
(...skipping 59 matching lines...) Expand 10 before | Expand all | Expand 10 after
2813 Methods 2599 Methods
2814 ------- 2600 -------
2815 2601
2816 .. index:: object: method 2602 .. index:: object: method
2817 2603
2818 Methods are functions that are called using the attribute notation. There are 2604 Methods are functions that are called using the attribute notation. There are
2819 two flavors: built-in methods (such as :meth:`append` on lists) and class 2605 two flavors: built-in methods (such as :meth:`append` on lists) and class
2820 instance methods. Built-in methods are described with the types that support 2606 instance methods. Built-in methods are described with the types that support
2821 them. 2607 them.
2822 2608
2823 The implementation adds two special read-only attributes to class instance 2609 If you access a method (a function defined in a class namespace) through an
2824 methods: ``m.im_self`` is the object on which the method operates, and 2610 instance, you get a special object: a :dfn:`bound method` (also called
2825 ``m.im_func`` is the function implementing the method. Calling ``m(arg-1, 2611 :dfn:`instance method`) object. When called, it will add the ``self`` argument
2826 arg-2, ..., arg-n)`` is completely equivalent to calling ``m.im_func(m.im_self, 2612 to the argument list. Bound methods have two special read-only attributes:
2827 arg-1, arg-2, ..., arg-n)``. 2613 ``m.__self__`` is the object on which the method operates, and ``m.__func__`` is
2828 2614 the function implementing the method. Calling ``m(arg-1, arg-2, ..., arg-n)``
2829 Class instance methods are either *bound* or *unbound*, referring to whether the 2615 is completely equivalent to calling ``m.__func__(m.__self__, arg-1, arg-2, ...,
2830 method was accessed through an instance or a class, respectively. When a method 2616 arg-n)``.
2831 is unbound, its ``im_self`` attribute will be ``None`` and if called, an 2617
2832 explicit ``self`` object must be passed as the first argument. In this case, 2618 Like function objects, bound method objects support getting arbitrary
2833 ``self`` must be an instance of the unbound method's class (or a subclass of 2619 attributes. However, since method attributes are actually stored on the
2834 that class), otherwise a :exc:`TypeError` is raised. 2620 underlying function object (``meth.__func__``), setting method attributes on
2835 2621 bound methods is disallowed. Attempting to set a method attribute results in a
2836 Like function objects, methods objects support getting arbitrary attributes.
2837 However, since method attributes are actually stored on the underlying function
2838 object (``meth.im_func``), setting method attributes on either bound or unbound
2839 methods is disallowed. Attempting to set a method attribute results in a
2840 :exc:`TypeError` being raised. In order to set a method attribute, you need to 2622 :exc:`TypeError` being raised. In order to set a method attribute, you need to
2841 explicitly set it on the underlying function object:: 2623 explicitly set it on the underlying function object::
2842 2624
2843 class C: 2625 class C:
2844 def method(self): 2626 def method(self):
2845 pass 2627 pass
2846 2628
2847 c = C() 2629 c = C()
2848 c.method.im_func.whoami = 'my name is c' 2630 c.method.__func__.whoami = 'my name is c'
2849 2631
2850 See :ref:`types` for more information. 2632 See :ref:`types` for more information.
2851 2633
2852 2634
2853 .. _bltin-code-objects: 2635 .. _bltin-code-objects:
2854 2636
2855 Code Objects 2637 Code Objects
2856 ------------ 2638 ------------
2857 2639
2858 .. index:: object: code 2640 .. index:: object: code
2859 2641
2860 .. index:: 2642 .. index::
2861 builtin: compile 2643 builtin: compile
2862 single: func_code (function object attribute) 2644 single: __code__ (function object attribute)
2863 2645
2864 Code objects are used by the implementation to represent "pseudo-compiled" 2646 Code objects are used by the implementation to represent "pseudo-compiled"
2865 executable Python code such as a function body. They differ from function 2647 executable Python code such as a function body. They differ from function
2866 objects because they don't contain a reference to their global execution 2648 objects because they don't contain a reference to their global execution
2867 environment. Code objects are returned by the built-in :func:`compile` function 2649 environment. Code objects are returned by the built-in :func:`compile` function
2868 and can be extracted from function objects through their :attr:`func_code` 2650 and can be extracted from function objects through their :attr:`__code__`
2869 attribute. See also the :mod:`code` module. 2651 attribute. See also the :mod:`code` module.
2870 2652
2871 .. index:: 2653 .. index::
2872 statement: exec 2654 builtin: exec
2873 builtin: eval 2655 builtin: eval
2874 2656
2875 A code object can be executed or evaluated by passing it (instead of a source 2657 A code object can be executed or evaluated by passing it (instead of a source
2876 string) to the :keyword:`exec` statement or the built-in :func:`eval` function. 2658 string) to the :func:`exec` or :func:`eval` built-in functions.
2877 2659
2878 See :ref:`types` for more information. 2660 See :ref:`types` for more information.
2879 2661
2880 2662
2881 .. _bltin-type-objects: 2663 .. _bltin-type-objects:
2882 2664
2883 Type Objects 2665 Type Objects
2884 ------------ 2666 ------------
2885 2667
2886 .. index:: 2668 .. index::
2887 builtin: type 2669 builtin: type
2888 module: types 2670 module: types
2889 2671
2890 Type objects represent the various object types. An object's type is accessed 2672 Type objects represent the various object types. An object's type is accessed
2891 by the built-in function :func:`type`. There are no special operations on 2673 by the built-in function :func:`type`. There are no special operations on
2892 types. The standard module :mod:`types` defines names for all standard built-in 2674 types. The standard module :mod:`types` defines names for all standard built-in
2893 types. 2675 types.
2894 2676
2895 Types are written like this: ``<type 'int'>``. 2677 Types are written like this: ``<class 'int'>``.
2896 2678
2897 2679
2898 .. _bltin-null-object: 2680 .. _bltin-null-object:
2899 2681
2900 The Null Object 2682 The Null Object
2901 --------------- 2683 ---------------
2902 2684
2903 This object is returned by functions that don't explicitly return a value. It 2685 This object is returned by functions that don't explicitly return a value. It
2904 supports no special operations. There is exactly one null object, named 2686 supports no special operations. There is exactly one null object, named
2905 ``None`` (a built-in name). 2687 ``None`` (a built-in name).
2906 2688
2907 It is written as ``None``. 2689 It is written as ``None``.
2908 2690
2909 2691
2910 .. _bltin-ellipsis-object: 2692 .. _bltin-ellipsis-object:
2911 2693
2912 The Ellipsis Object 2694 The Ellipsis Object
2913 ------------------- 2695 -------------------
2914 2696
2915 This object is used by extended slice notation (see :ref:`slicings`). It 2697 This object is commonly used by slicing (see :ref:`slicings`). It supports no
2916 supports no special operations. There is exactly one ellipsis object, named 2698 special operations. There is exactly one ellipsis object, named
2917 :const:`Ellipsis` (a built-in name). 2699 :const:`Ellipsis` (a built-in name).
2918 2700
2919 It is written as ``Ellipsis``. 2701 It is written as ``Ellipsis`` or ``...``.
2920 2702
2921 2703
2922 Boolean Values 2704 Boolean Values
2923 -------------- 2705 --------------
2924 2706
2925 Boolean values are the two constant objects ``False`` and ``True``. They are 2707 Boolean values are the two constant objects ``False`` and ``True``. They are
2926 used to represent truth values (although other values can also be considered 2708 used to represent truth values (although other values can also be considered
2927 false or true). In numeric contexts (for example when used as the argument to 2709 false or true). In numeric contexts (for example when used as the argument to
2928 an arithmetic operator), they behave like the integers 0 and 1, respectively. 2710 an arithmetic operator), they behave like the integers 0 and 1, respectively.
2929 The built-in function :func:`bool` can be used to cast any value to a Boolean, 2711 The built-in function :func:`bool` can be used to cast any value to a Boolean,
(...skipping 26 matching lines...) Expand all
2956 types, where they are relevant. Some of these are not reported by the 2738 types, where they are relevant. Some of these are not reported by the
2957 :func:`dir` built-in function. 2739 :func:`dir` built-in function.
2958 2740
2959 2741
2960 .. attribute:: object.__dict__ 2742 .. attribute:: object.__dict__
2961 2743
2962 A dictionary or other mapping object used to store an object's (writable) 2744 A dictionary or other mapping object used to store an object's (writable)
2963 attributes. 2745 attributes.
2964 2746
2965 2747
2966 .. attribute:: object.__methods__
2967
2968 .. deprecated:: 2.2
2969 Use the built-in function :func:`dir` to get a list of an object's attribu tes.
2970 This attribute is no longer available.
2971
2972
2973 .. attribute:: object.__members__
2974
2975 .. deprecated:: 2.2
2976 Use the built-in function :func:`dir` to get a list of an object's attribu tes.
2977 This attribute is no longer available.
2978
2979
2980 .. attribute:: instance.__class__ 2748 .. attribute:: instance.__class__
2981 2749
2982 The class to which a class instance belongs. 2750 The class to which a class instance belongs.
2983 2751
2984 2752
2985 .. attribute:: class.__bases__ 2753 .. attribute:: class.__bases__
2986 2754
2987 The tuple of base classes of a class object. 2755 The tuple of base classes of a class object.
2988 2756
2989 2757
(...skipping 32 matching lines...) Expand 10 before | Expand all | Expand 10 after
3022 .. [#] Additional information on these special methods may be found in the Pytho n 2790 .. [#] Additional information on these special methods may be found in the Pytho n
3023 Reference Manual (:ref:`customization`). 2791 Reference Manual (:ref:`customization`).
3024 2792
3025 .. [#] As a consequence, the list ``[1, 2]`` is considered equal to ``[1.0, 2.0] ``, and 2793 .. [#] As a consequence, the list ``[1, 2]`` is considered equal to ``[1.0, 2.0] ``, and
3026 similarly for tuples. 2794 similarly for tuples.
3027 2795
3028 .. [#] They must have since the parser can't tell the type of the operands. 2796 .. [#] They must have since the parser can't tell the type of the operands.
3029 2797
3030 .. [#] To format only a tuple you should therefore provide a singleton tuple who se only 2798 .. [#] To format only a tuple you should therefore provide a singleton tuple who se only
3031 element is the tuple to be formatted. 2799 element is the tuple to be formatted.
3032
3033 .. [#] The advantage of leaving the newline on is that returning an empty string is
3034 then an unambiguous EOF indication. It is also possible (in cases where it
3035 might matter, for example, if you want to make an exact copy of a file while
3036 scanning its lines) to tell whether the last line of a file ended in a newlin e
3037 or not (yes this happens!).
LEFTRIGHT
« no previous file | no next file » | Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Toggle Comments ('s')

RSS Feeds Recent Issues | This issue
This is Rietveld 894c83f36cb7+