Linux ip-148-66-134-25.ip.secureserver.net 3.10.0-1160.119.1.el7.tuxcare.els11.x86_64 #1 SMP Sun Nov 3 09:06:59 UTC 2024 x86_64
Apache
: 148.66.134.25 | : 3.12.146.100
66 Domain
8.0.30
amvm
www.github.com/MadExploits
Terminal
AUTO ROOT
Adminer
Backdoor Destroyer
Linux Exploit
Lock Shell
Lock File
Create User
CREATE RDP
PHP Mailer
BACKCONNECT
UNLOCK SHELL
HASH IDENTIFIER
CPANEL RESET
BLACK DEFEND!
README
+ Create Folder
+ Create File
/
usr /
share /
doc /
python-docs-2.7.5 /
html /
library /
[ HOME SHELL ]
Name
Size
Permission
Action
2to3.html
49.27
KB
-rw-r--r--
__builtin__.html
10.26
KB
-rw-r--r--
__future__.html
13.79
KB
-rw-r--r--
__main__.html
7.05
KB
-rw-r--r--
_winreg.html
59.21
KB
-rw-r--r--
abc.html
23.9
KB
-rw-r--r--
aepack.html
13.16
KB
-rw-r--r--
aetools.html
14.91
KB
-rw-r--r--
aetypes.html
18.88
KB
-rw-r--r--
aifc.html
22.4
KB
-rw-r--r--
al.html
17.34
KB
-rw-r--r--
allos.html
33.72
KB
-rw-r--r--
anydbm.html
16.33
KB
-rw-r--r--
archiving.html
9.26
KB
-rw-r--r--
argparse.html
237.62
KB
-rw-r--r--
array.html
29.29
KB
-rw-r--r--
ast.html
34.98
KB
-rw-r--r--
asynchat.html
31.43
KB
-rw-r--r--
asyncore.html
36.51
KB
-rw-r--r--
atexit.html
16.8
KB
-rw-r--r--
audioop.html
31.36
KB
-rw-r--r--
autogil.html
8.19
KB
-rw-r--r--
base64.html
19.67
KB
-rw-r--r--
basehttpserver.html
34.04
KB
-rw-r--r--
bastion.html
11.04
KB
-rw-r--r--
bdb.html
36.68
KB
-rw-r--r--
binascii.html
20.67
KB
-rw-r--r--
binhex.html
10.58
KB
-rw-r--r--
bisect.html
23.24
KB
-rw-r--r--
bsddb.html
26.43
KB
-rw-r--r--
bz2.html
26.08
KB
-rw-r--r--
calendar.html
37.79
KB
-rw-r--r--
carbon.html
48.94
KB
-rw-r--r--
cd.html
27.96
KB
-rw-r--r--
cgi.html
49.92
KB
-rw-r--r--
cgihttpserver.html
13.1
KB
-rw-r--r--
cgitb.html
11.41
KB
-rw-r--r--
chunk.html
14.66
KB
-rw-r--r--
cmath.html
25.63
KB
-rw-r--r--
cmd.html
26.09
KB
-rw-r--r--
code.html
24.58
KB
-rw-r--r--
codecs.html
100.64
KB
-rw-r--r--
codeop.html
14.84
KB
-rw-r--r--
collections.html
133.96
KB
-rw-r--r--
colorpicker.html
7.52
KB
-rw-r--r--
colorsys.html
11.04
KB
-rw-r--r--
commands.html
14.36
KB
-rw-r--r--
compileall.html
16.83
KB
-rw-r--r--
compiler.html
67.75
KB
-rw-r--r--
configparser.html
62.13
KB
-rw-r--r--
constants.html
12.83
KB
-rw-r--r--
contextlib.html
19.39
KB
-rw-r--r--
cookie.html
39.07
KB
-rw-r--r--
cookielib.html
83.82
KB
-rw-r--r--
copy.html
12.19
KB
-rw-r--r--
copy_reg.html
13.76
KB
-rw-r--r--
crypt.html
10.04
KB
-rw-r--r--
crypto.html
7.59
KB
-rw-r--r--
csv.html
67.37
KB
-rw-r--r--
ctypes.html
238.78
KB
-rw-r--r--
curses.ascii.html
22.29
KB
-rw-r--r--
curses.html
146.63
KB
-rw-r--r--
curses.panel.html
14.39
KB
-rw-r--r--
custominterp.html
7.62
KB
-rw-r--r--
datatypes.html
16.84
KB
-rw-r--r--
datetime.html
226.59
KB
-rw-r--r--
dbhash.html
15.48
KB
-rw-r--r--
dbm.html
12.07
KB
-rw-r--r--
debug.html
10.15
KB
-rw-r--r--
decimal.html
194.44
KB
-rw-r--r--
development.html
14.17
KB
-rw-r--r--
difflib.html
84.83
KB
-rw-r--r--
dircache.html
11.41
KB
-rw-r--r--
dis.html
69.95
KB
-rw-r--r--
distutils.html
8.05
KB
-rw-r--r--
dl.html
16.33
KB
-rw-r--r--
doctest.html
165.54
KB
-rw-r--r--
docxmlrpcserver.html
16.43
KB
-rw-r--r--
dumbdbm.html
14.02
KB
-rw-r--r--
dummy_thread.html
9.43
KB
-rw-r--r--
dummy_threading.html
8.37
KB
-rw-r--r--
easydialogs.html
30.55
KB
-rw-r--r--
email-examples.html
45.65
KB
-rw-r--r--
email.charset.html
26.8
KB
-rw-r--r--
email.encoders.html
11.86
KB
-rw-r--r--
email.errors.html
15.77
KB
-rw-r--r--
email.generator.html
20.77
KB
-rw-r--r--
email.header.html
26.92
KB
-rw-r--r--
email.html
44.24
KB
-rw-r--r--
email.iterators.html
11.52
KB
-rw-r--r--
email.message.html
63.16
KB
-rw-r--r--
email.mime.html
27.93
KB
-rw-r--r--
email.parser.html
30.45
KB
-rw-r--r--
email.util.html
24.46
KB
-rw-r--r--
errno.html
37.99
KB
-rw-r--r--
exceptions.html
56.13
KB
-rw-r--r--
fcntl.html
22.67
KB
-rw-r--r--
filecmp.html
22.3
KB
-rw-r--r--
fileformats.html
9.14
KB
-rw-r--r--
fileinput.html
24.28
KB
-rw-r--r--
filesys.html
10.2
KB
-rw-r--r--
fl.html
49.92
KB
-rw-r--r--
fm.html
11.91
KB
-rw-r--r--
fnmatch.html
14.58
KB
-rw-r--r--
formatter.html
34.06
KB
-rw-r--r--
fpectl.html
16.01
KB
-rw-r--r--
fpformat.html
10.59
KB
-rw-r--r--
fractions.html
22.61
KB
-rw-r--r--
framework.html
33.34
KB
-rw-r--r--
frameworks.html
7.14
KB
-rw-r--r--
ftplib.html
43.99
KB
-rw-r--r--
functions.html
183.14
KB
-rw-r--r--
functools.html
27.17
KB
-rw-r--r--
future_builtins.html
13.04
KB
-rw-r--r--
gc.html
25.75
KB
-rw-r--r--
gdbm.html
15.96
KB
-rw-r--r--
gensuitemodule.html
11.51
KB
-rw-r--r--
getopt.html
23.66
KB
-rw-r--r--
getpass.html
10.65
KB
-rw-r--r--
gettext.html
78.76
KB
-rw-r--r--
gl.html
22.09
KB
-rw-r--r--
glob.html
13.26
KB
-rw-r--r--
grp.html
10.49
KB
-rw-r--r--
gzip.html
18.99
KB
-rw-r--r--
hashlib.html
18.2
KB
-rw-r--r--
heapq.html
31.61
KB
-rw-r--r--
hmac.html
10.46
KB
-rw-r--r--
hotshot.html
18.65
KB
-rw-r--r--
htmllib.html
25.32
KB
-rw-r--r--
htmlparser.html
39.11
KB
-rw-r--r--
httplib.html
62.95
KB
-rw-r--r--
i18n.html
9.52
KB
-rw-r--r--
ic.html
17.17
KB
-rw-r--r--
idle.html
20.9
KB
-rw-r--r--
imageop.html
14.76
KB
-rw-r--r--
imaplib.html
51.99
KB
-rw-r--r--
imgfile.html
11.71
KB
-rw-r--r--
imghdr.html
11.3
KB
-rw-r--r--
imp.html
34.34
KB
-rw-r--r--
importlib.html
8.26
KB
-rw-r--r--
imputil.html
31.81
KB
-rw-r--r--
index.html
72.78
KB
-rw-r--r--
inspect.html
50.71
KB
-rw-r--r--
internet.html
24.87
KB
-rw-r--r--
intro.html
8.93
KB
-rw-r--r--
io.html
98.13
KB
-rw-r--r--
ipc.html
13.41
KB
-rw-r--r--
itertools.html
115.91
KB
-rw-r--r--
jpeg.html
12.74
KB
-rw-r--r--
json.html
67.04
KB
-rw-r--r--
keyword.html
7.68
KB
-rw-r--r--
language.html
11.03
KB
-rw-r--r--
linecache.html
10.59
KB
-rw-r--r--
locale.html
55.14
KB
-rw-r--r--
logging.config.html
63.36
KB
-rw-r--r--
logging.handlers.html
69.64
KB
-rw-r--r--
logging.html
95.64
KB
-rw-r--r--
mac.html
21.79
KB
-rw-r--r--
macos.html
14.76
KB
-rw-r--r--
macosa.html
12.96
KB
-rw-r--r--
macostools.html
15.52
KB
-rw-r--r--
macpath.html
7.76
KB
-rw-r--r--
mailbox.html
156.75
KB
-rw-r--r--
mailcap.html
13.21
KB
-rw-r--r--
markup.html
18.77
KB
-rw-r--r--
marshal.html
17.98
KB
-rw-r--r--
math.html
39.24
KB
-rw-r--r--
md5.html
13.97
KB
-rw-r--r--
mhlib.html
21.54
KB
-rw-r--r--
mimetools.html
19.25
KB
-rw-r--r--
mimetypes.html
28.39
KB
-rw-r--r--
mimewriter.html
15.02
KB
-rw-r--r--
mimify.html
13.36
KB
-rw-r--r--
miniaeframe.html
12.2
KB
-rw-r--r--
misc.html
6.87
KB
-rw-r--r--
mm.html
9.03
KB
-rw-r--r--
mmap.html
28.36
KB
-rw-r--r--
modulefinder.html
15.31
KB
-rw-r--r--
modules.html
8.46
KB
-rw-r--r--
msilib.html
52.43
KB
-rw-r--r--
msvcrt.html
19.37
KB
-rw-r--r--
multifile.html
24.3
KB
-rw-r--r--
multiprocessing.html
365.71
KB
-rw-r--r--
mutex.html
11.23
KB
-rw-r--r--
netdata.html
16.98
KB
-rw-r--r--
netrc.html
12.3
KB
-rw-r--r--
new.html
12.12
KB
-rw-r--r--
nis.html
10.64
KB
-rw-r--r--
nntplib.html
41.92
KB
-rw-r--r--
numbers.html
37.75
KB
-rw-r--r--
numeric.html
13.55
KB
-rw-r--r--
operator.html
82
KB
-rw-r--r--
optparse.html
222.56
KB
-rw-r--r--
os.html
214.25
KB
-rw-r--r--
os.path.html
38.34
KB
-rw-r--r--
ossaudiodev.html
41.5
KB
-rw-r--r--
othergui.html
9.08
KB
-rw-r--r--
parser.html
39.36
KB
-rw-r--r--
pdb.html
33.96
KB
-rw-r--r--
persistence.html
14.87
KB
-rw-r--r--
pickle.html
102.27
KB
-rw-r--r--
pickletools.html
10.63
KB
-rw-r--r--
pipes.html
18.01
KB
-rw-r--r--
pkgutil.html
25.11
KB
-rw-r--r--
platform.html
28.37
KB
-rw-r--r--
plistlib.html
17.03
KB
-rw-r--r--
popen2.html
25.43
KB
-rw-r--r--
poplib.html
22.32
KB
-rw-r--r--
posix.html
14.41
KB
-rw-r--r--
posixfile.html
19.76
KB
-rw-r--r--
pprint.html
29.92
KB
-rw-r--r--
profile.html
63.56
KB
-rw-r--r--
pty.html
9.48
KB
-rw-r--r--
pwd.html
11.43
KB
-rw-r--r--
py_compile.html
11.12
KB
-rw-r--r--
pyclbr.html
14.71
KB
-rw-r--r--
pydoc.html
11.48
KB
-rw-r--r--
pyexpat.html
71.53
KB
-rw-r--r--
python.html
12.27
KB
-rw-r--r--
queue.html
24.22
KB
-rw-r--r--
quopri.html
11.9
KB
-rw-r--r--
random.html
37.83
KB
-rw-r--r--
re.html
134.74
KB
-rw-r--r--
readline.html
28.24
KB
-rw-r--r--
repr.html
20.43
KB
-rw-r--r--
resource.html
26.48
KB
-rw-r--r--
restricted.html
11.65
KB
-rw-r--r--
rexec.html
37.41
KB
-rw-r--r--
rfc822.html
42.22
KB
-rw-r--r--
rlcompleter.html
13.51
KB
-rw-r--r--
robotparser.html
12.27
KB
-rw-r--r--
runpy.html
19.34
KB
-rw-r--r--
sched.html
18.54
KB
-rw-r--r--
scrolledtext.html
9.32
KB
-rw-r--r--
select.html
39.67
KB
-rw-r--r--
sets.html
36.92
KB
-rw-r--r--
sgi.html
9.71
KB
-rw-r--r--
sgmllib.html
30.77
KB
-rw-r--r--
sha.html
12.09
KB
-rw-r--r--
shelve.html
27.02
KB
-rw-r--r--
shlex.html
32.1
KB
-rw-r--r--
shutil.html
40.22
KB
-rw-r--r--
signal.html
31.14
KB
-rw-r--r--
simplehttpserver.html
18.41
KB
-rw-r--r--
simplexmlrpcserver.html
31.39
KB
-rw-r--r--
site.html
23.64
KB
-rw-r--r--
smtpd.html
12.46
KB
-rw-r--r--
smtplib.html
42.13
KB
-rw-r--r--
sndhdr.html
10.02
KB
-rw-r--r--
socket.html
106.34
KB
-rw-r--r--
socketserver.html
59.83
KB
-rw-r--r--
someos.html
15.11
KB
-rw-r--r--
spwd.html
10.33
KB
-rw-r--r--
sqlite3.html
139.5
KB
-rw-r--r--
ssl.html
65.62
KB
-rw-r--r--
stat.html
32.31
KB
-rw-r--r--
statvfs.html
10.6
KB
-rw-r--r--
stdtypes.html
260.4
KB
-rw-r--r--
string.html
106.65
KB
-rw-r--r--
stringio.html
18.81
KB
-rw-r--r--
stringprep.html
16.13
KB
-rw-r--r--
strings.html
14.93
KB
-rw-r--r--
struct.html
40.88
KB
-rw-r--r--
subprocess.html
84.91
KB
-rw-r--r--
sun.html
6.84
KB
-rw-r--r--
sunau.html
27.1
KB
-rw-r--r--
sunaudio.html
17.79
KB
-rw-r--r--
symbol.html
7.66
KB
-rw-r--r--
symtable.html
22.94
KB
-rw-r--r--
sys.html
98.7
KB
-rw-r--r--
sysconfig.html
23.84
KB
-rw-r--r--
syslog.html
17.92
KB
-rw-r--r--
tabnanny.html
10.63
KB
-rw-r--r--
tarfile.html
78.68
KB
-rw-r--r--
telnetlib.html
25.48
KB
-rw-r--r--
tempfile.html
29.42
KB
-rw-r--r--
termios.html
16.01
KB
-rw-r--r--
test.html
52.62
KB
-rw-r--r--
textwrap.html
27.25
KB
-rw-r--r--
thread.html
20.47
KB
-rw-r--r--
threading.html
76.69
KB
-rw-r--r--
time.html
56.93
KB
-rw-r--r--
timeit.html
36.27
KB
-rw-r--r--
tix.html
46.96
KB
-rw-r--r--
tk.html
23.64
KB
-rw-r--r--
tkinter.html
67.67
KB
-rw-r--r--
token.html
19.62
KB
-rw-r--r--
tokenize.html
18.45
KB
-rw-r--r--
trace.html
25.54
KB
-rw-r--r--
traceback.html
33.44
KB
-rw-r--r--
ttk.html
101.75
KB
-rw-r--r--
tty.html
9.06
KB
-rw-r--r--
turtle.html
211.74
KB
-rw-r--r--
types.html
27.59
KB
-rw-r--r--
undoc.html
23.16
KB
-rw-r--r--
unicodedata.html
18.55
KB
-rw-r--r--
unittest.html
202.85
KB
-rw-r--r--
unix.html
10.55
KB
-rw-r--r--
urllib.html
58.68
KB
-rw-r--r--
urllib2.html
100.58
KB
-rw-r--r--
urlparse.html
40.41
KB
-rw-r--r--
user.html
11.83
KB
-rw-r--r--
userdict.html
29.73
KB
-rw-r--r--
uu.html
11.03
KB
-rw-r--r--
uuid.html
28.19
KB
-rw-r--r--
warnings.html
46.6
KB
-rw-r--r--
wave.html
22.22
KB
-rw-r--r--
weakref.html
36.52
KB
-rw-r--r--
webbrowser.html
23.07
KB
-rw-r--r--
whichdb.html
8.85
KB
-rw-r--r--
windows.html
9.33
KB
-rw-r--r--
winsound.html
18.75
KB
-rw-r--r--
wsgiref.html
81.04
KB
-rw-r--r--
xdrlib.html
29.94
KB
-rw-r--r--
xml.dom.html
89.04
KB
-rw-r--r--
xml.dom.minidom.html
40.42
KB
-rw-r--r--
xml.dom.pulldom.html
12.71
KB
-rw-r--r--
xml.etree.elementtree.html
93.22
KB
-rw-r--r--
xml.html
16.49
KB
-rw-r--r--
xml.sax.handler.html
38.63
KB
-rw-r--r--
xml.sax.html
20.22
KB
-rw-r--r--
xml.sax.reader.html
39.09
KB
-rw-r--r--
xml.sax.utils.html
14.26
KB
-rw-r--r--
xmlrpclib.html
60.79
KB
-rw-r--r--
zipfile.html
53.14
KB
-rw-r--r--
zipimport.html
20.42
KB
-rw-r--r--
zlib.html
25.46
KB
-rw-r--r--
Delete
Unzip
Zip
${this.title}
Close
Code Editor : stdtypes.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>5. Built-in Types — Python 2.7.5 documentation</title> <link rel="stylesheet" href="../_static/default.css" type="text/css" /> <link rel="stylesheet" href="../_static/pygments.css" type="text/css" /> <script type="text/javascript"> var DOCUMENTATION_OPTIONS = { URL_ROOT: '../', VERSION: '2.7.5', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', HAS_SOURCE: true }; </script> <script type="text/javascript" src="../_static/jquery.js"></script> <script type="text/javascript" src="../_static/underscore.js"></script> <script type="text/javascript" src="../_static/doctools.js"></script> <script type="text/javascript" src="../_static/sidebar.js"></script> <link rel="search" type="application/opensearchdescription+xml" title="Search within Python 2.7.5 documentation" href="../_static/opensearch.xml"/> <link rel="author" title="About these documents" href="../about.html" /> <link rel="copyright" title="Copyright" href="../copyright.html" /> <link rel="top" title="Python 2.7.5 documentation" href="../index.html" /> <link rel="up" title="The Python Standard Library" href="index.html" /> <link rel="next" title="6. Built-in Exceptions" href="exceptions.html" /> <link rel="prev" title="4. Built-in Constants" href="constants.html" /> <link rel="shortcut icon" type="image/png" href="../_static/py.png" /> <script type="text/javascript" src="../_static/copybutton.js"></script> </head> <body> <div class="related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" accesskey="I">index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="exceptions.html" title="6. Built-in Exceptions" accesskey="N">next</a> |</li> <li class="right" > <a href="constants.html" title="4. Built-in Constants" accesskey="P">previous</a> |</li> <li><img src="../_static/py.png" alt="" style="vertical-align: middle; margin-top: -1px"/></li> <li><a href="http://www.python.org/">Python</a> »</li> <li> <a href="../index.html">Python 2.7.5 documentation</a> » </li> <li><a href="index.html" accesskey="U">The Python Standard Library</a> »</li> </ul> </div> <div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body"> <div class="section" id="built-in-types"> <span id="bltin-types"></span><h1>5. Built-in Types<a class="headerlink" href="#built-in-types" title="Permalink to this headline">¶</a></h1> <p>The following sections describe the standard types that are built into the interpreter.</p> <div class="admonition note"> <p class="first admonition-title">Note</p> <p class="last">Historically (until release 2.2), Python’s built-in types have differed from user-defined types because it was not possible to use the built-in types as the basis for object-oriented inheritance. This limitation no longer exists.</p> </div> <p id="index-0">The principal built-in types are numerics, sequences, mappings, files, classes, instances and exceptions.</p> <p id="index-1">Some operations are supported by several object types; in particular, practically all objects can be compared, tested for truth value, and converted to a string (with the <a class="reference internal" href="functions.html#func-repr"><em>repr()</em></a> function or the slightly different <a class="reference internal" href="functions.html#str" title="str"><tt class="xref py py-func docutils literal"><span class="pre">str()</span></tt></a> function). The latter function is implicitly used when an object is written by the <a class="reference internal" href="functions.html#print" title="print"><tt class="xref py py-func docutils literal"><span class="pre">print()</span></tt></a> function.</p> <div class="section" id="truth-value-testing"> <span id="truth"></span><h2>5.1. Truth Value Testing<a class="headerlink" href="#truth-value-testing" title="Permalink to this headline">¶</a></h2> <p id="index-2">Any object can be tested for truth value, for use in an <a class="reference internal" href="../reference/compound_stmts.html#if"><tt class="xref std std-keyword docutils literal"><span class="pre">if</span></tt></a> or <a class="reference internal" href="../reference/compound_stmts.html#while"><tt class="xref std std-keyword docutils literal"><span class="pre">while</span></tt></a> condition or as operand of the Boolean operations below. The following values are considered false:</p> <blockquote> <div></div></blockquote> <ul id="index-3"> <li><p class="first"><tt class="docutils literal"><span class="pre">None</span></tt></p> </li> <li id="index-4"><p class="first"><tt class="docutils literal"><span class="pre">False</span></tt></p> </li> <li><p class="first">zero of any numeric type, for example, <tt class="docutils literal"><span class="pre">0</span></tt>, <tt class="docutils literal"><span class="pre">0L</span></tt>, <tt class="docutils literal"><span class="pre">0.0</span></tt>, <tt class="docutils literal"><span class="pre">0j</span></tt>.</p> </li> <li><p class="first">any empty sequence, for example, <tt class="docutils literal"><span class="pre">''</span></tt>, <tt class="docutils literal"><span class="pre">()</span></tt>, <tt class="docutils literal"><span class="pre">[]</span></tt>.</p> </li> <li><p class="first">any empty mapping, for example, <tt class="docutils literal"><span class="pre">{}</span></tt>.</p> </li> <li><p class="first">instances of user-defined classes, if the class defines a <a class="reference internal" href="../reference/datamodel.html#object.__nonzero__" title="object.__nonzero__"><tt class="xref py py-meth docutils literal"><span class="pre">__nonzero__()</span></tt></a> or <a class="reference internal" href="../reference/datamodel.html#object.__len__" title="object.__len__"><tt class="xref py py-meth docutils literal"><span class="pre">__len__()</span></tt></a> method, when that method returns the integer zero or <a class="reference internal" href="functions.html#bool" title="bool"><tt class="xref py py-class docutils literal"><span class="pre">bool</span></tt></a> value <tt class="docutils literal"><span class="pre">False</span></tt>. <a class="footnote-reference" href="#id12" id="id1">[1]</a></p> </li> </ul> <p id="index-5">All other values are considered true — so objects of many types are always true.</p> <p id="index-6">Operations and built-in functions that have a Boolean result always return <tt class="docutils literal"><span class="pre">0</span></tt> or <tt class="docutils literal"><span class="pre">False</span></tt> for false and <tt class="docutils literal"><span class="pre">1</span></tt> or <tt class="docutils literal"><span class="pre">True</span></tt> for true, unless otherwise stated. (Important exception: the Boolean operations <tt class="docutils literal"><span class="pre">or</span></tt> and <tt class="docutils literal"><span class="pre">and</span></tt> always return one of their operands.)</p> </div> <div class="section" id="boolean-operations-and-or-not"> <span id="boolean"></span><h2>5.2. Boolean Operations — <a class="reference internal" href="../reference/expressions.html#and"><tt class="xref std std-keyword docutils literal"><span class="pre">and</span></tt></a>, <a class="reference internal" href="../reference/expressions.html#or"><tt class="xref std std-keyword docutils literal"><span class="pre">or</span></tt></a>, <a class="reference internal" href="../reference/expressions.html#not"><tt class="xref std std-keyword docutils literal"><span class="pre">not</span></tt></a><a class="headerlink" href="#boolean-operations-and-or-not" title="Permalink to this headline">¶</a></h2> <p id="index-7">These are the Boolean operations, ordered by ascending priority:</p> <table border="1" class="docutils"> <colgroup> <col width="25%" /> <col width="62%" /> <col width="13%" /> </colgroup> <thead valign="bottom"> <tr class="row-odd"><th class="head">Operation</th> <th class="head">Result</th> <th class="head">Notes</th> </tr> </thead> <tbody valign="top"> <tr class="row-even"><td><tt class="docutils literal"><span class="pre">x</span> <span class="pre">or</span> <span class="pre">y</span></tt></td> <td>if <em>x</em> is false, then <em>y</em>, else <em>x</em></td> <td>(1)</td> </tr> <tr class="row-odd"><td><tt class="docutils literal"><span class="pre">x</span> <span class="pre">and</span> <span class="pre">y</span></tt></td> <td>if <em>x</em> is false, then <em>x</em>, else <em>y</em></td> <td>(2)</td> </tr> <tr class="row-even"><td><tt class="docutils literal"><span class="pre">not</span> <span class="pre">x</span></tt></td> <td>if <em>x</em> is false, then <tt class="docutils literal"><span class="pre">True</span></tt>, else <tt class="docutils literal"><span class="pre">False</span></tt></td> <td>(3)</td> </tr> </tbody> </table> <p id="index-8">Notes:</p> <ol class="arabic simple"> <li>This is a short-circuit operator, so it only evaluates the second argument if the first one is <a class="reference internal" href="constants.html#False" title="False"><tt class="xref py py-const docutils literal"><span class="pre">False</span></tt></a>.</li> <li>This is a short-circuit operator, so it only evaluates the second argument if the first one is <a class="reference internal" href="constants.html#True" title="True"><tt class="xref py py-const docutils literal"><span class="pre">True</span></tt></a>.</li> <li><tt class="docutils literal"><span class="pre">not</span></tt> has a lower priority than non-Boolean operators, so <tt class="docutils literal"><span class="pre">not</span> <span class="pre">a</span> <span class="pre">==</span> <span class="pre">b</span></tt> is interpreted as <tt class="docutils literal"><span class="pre">not</span> <span class="pre">(a</span> <span class="pre">==</span> <span class="pre">b)</span></tt>, and <tt class="docutils literal"><span class="pre">a</span> <span class="pre">==</span> <span class="pre">not</span> <span class="pre">b</span></tt> is a syntax error.</li> </ol> </div> <div class="section" id="comparisons"> <span id="stdcomparisons"></span><h2>5.3. Comparisons<a class="headerlink" href="#comparisons" title="Permalink to this headline">¶</a></h2> <p id="index-9">Comparison operations are supported by all objects. They all have the same priority (which is higher than that of the Boolean operations). Comparisons can be chained arbitrarily; for example, <tt class="docutils literal"><span class="pre">x</span> <span class="pre"><</span> <span class="pre">y</span> <span class="pre"><=</span> <span class="pre">z</span></tt> is equivalent to <tt class="docutils literal"><span class="pre">x</span> <span class="pre"><</span> <span class="pre">y</span> <span class="pre">and</span> <span class="pre">y</span> <span class="pre"><=</span> <span class="pre">z</span></tt>, except that <em>y</em> is evaluated only once (but in both cases <em>z</em> is not evaluated at all when <tt class="docutils literal"><span class="pre">x</span> <span class="pre"><</span> <span class="pre">y</span></tt> is found to be false).</p> <p>This table summarizes the comparison operations:</p> <table border="1" class="docutils"> <colgroup> <col width="27%" /> <col width="57%" /> <col width="16%" /> </colgroup> <thead valign="bottom"> <tr class="row-odd"><th class="head">Operation</th> <th class="head">Meaning</th> <th class="head">Notes</th> </tr> </thead> <tbody valign="top"> <tr class="row-even"><td><tt class="docutils literal"><span class="pre"><</span></tt></td> <td>strictly less than</td> <td> </td> </tr> <tr class="row-odd"><td><tt class="docutils literal"><span class="pre"><=</span></tt></td> <td>less than or equal</td> <td> </td> </tr> <tr class="row-even"><td><tt class="docutils literal"><span class="pre">></span></tt></td> <td>strictly greater than</td> <td> </td> </tr> <tr class="row-odd"><td><tt class="docutils literal"><span class="pre">>=</span></tt></td> <td>greater than or equal</td> <td> </td> </tr> <tr class="row-even"><td><tt class="docutils literal"><span class="pre">==</span></tt></td> <td>equal</td> <td> </td> </tr> <tr class="row-odd"><td><tt class="docutils literal"><span class="pre">!=</span></tt></td> <td>not equal</td> <td>(1)</td> </tr> <tr class="row-even"><td><tt class="docutils literal"><span class="pre">is</span></tt></td> <td>object identity</td> <td> </td> </tr> <tr class="row-odd"><td><tt class="docutils literal"><span class="pre">is</span> <span class="pre">not</span></tt></td> <td>negated object identity</td> <td> </td> </tr> </tbody> </table> <p>Notes:</p> <ol class="arabic simple"> <li><tt class="docutils literal"><span class="pre">!=</span></tt> can also be written <tt class="docutils literal"><span class="pre"><></span></tt>, but this is an obsolete usage kept for backwards compatibility only. New code should always use <tt class="docutils literal"><span class="pre">!=</span></tt>.</li> </ol> <p id="index-10">Objects of different types, except different numeric types and different string types, never compare equal; such objects are ordered consistently but arbitrarily (so that sorting a heterogeneous array yields a consistent result). Furthermore, some types (for example, file objects) support only a degenerate notion of comparison where any two objects of that type are unequal. Again, such objects are ordered arbitrarily but consistently. The <tt class="docutils literal"><span class="pre"><</span></tt>, <tt class="docutils literal"><span class="pre"><=</span></tt>, <tt class="docutils literal"><span class="pre">></span></tt> and <tt class="docutils literal"><span class="pre">>=</span></tt> operators will raise a <a class="reference internal" href="exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><tt class="xref py py-exc docutils literal"><span class="pre">TypeError</span></tt></a> exception when any operand is a complex number.</p> <p id="index-11">Instances of a class normally compare as non-equal unless the class defines the <a class="reference internal" href="../reference/datamodel.html#object.__cmp__" title="object.__cmp__"><tt class="xref py py-meth docutils literal"><span class="pre">__cmp__()</span></tt></a> method. Refer to <a class="reference internal" href="../reference/datamodel.html#customization"><em>Basic customization</em></a>) for information on the use of this method to effect object comparisons.</p> <div class="impl-detail compound"> <p><strong>CPython implementation detail:</strong> Objects of different types except numbers are ordered by their type names; objects of the same types that don’t support proper comparison are ordered by their address.</p> </div> <p id="index-12">Two more operations with the same syntactic priority, <tt class="docutils literal"><span class="pre">in</span></tt> and <tt class="docutils literal"><span class="pre">not</span> <span class="pre">in</span></tt>, are supported only by sequence types (below).</p> </div> <div class="section" id="numeric-types-int-float-long-complex"> <span id="typesnumeric"></span><h2>5.4. Numeric Types — <a class="reference internal" href="functions.html#int" title="int"><tt class="xref py py-class docutils literal"><span class="pre">int</span></tt></a>, <a class="reference internal" href="functions.html#float" title="float"><tt class="xref py py-class docutils literal"><span class="pre">float</span></tt></a>, <a class="reference internal" href="functions.html#long" title="long"><tt class="xref py py-class docutils literal"><span class="pre">long</span></tt></a>, <a class="reference internal" href="functions.html#complex" title="complex"><tt class="xref py py-class docutils literal"><span class="pre">complex</span></tt></a><a class="headerlink" href="#numeric-types-int-float-long-complex" title="Permalink to this headline">¶</a></h2> <p id="index-13">There are four distinct numeric types: <em class="dfn">plain integers</em>, <em class="dfn">long integers</em>, <em class="dfn">floating point numbers</em>, and <em class="dfn">complex numbers</em>. In addition, Booleans are a subtype of plain integers. Plain integers (also just called <em class="dfn">integers</em>) are implemented using <tt class="xref c c-type docutils literal"><span class="pre">long</span></tt> in C, which gives them at least 32 bits of precision (<tt class="docutils literal"><span class="pre">sys.maxint</span></tt> is always set to the maximum plain integer value for the current platform, the minimum value is <tt class="docutils literal"><span class="pre">-sys.maxint</span> <span class="pre">-</span> <span class="pre">1</span></tt>). Long integers have unlimited precision. Floating point numbers are usually implemented using <tt class="xref c c-type docutils literal"><span class="pre">double</span></tt> in C; information about the precision and internal representation of floating point numbers for the machine on which your program is running is available in <a class="reference internal" href="sys.html#sys.float_info" title="sys.float_info"><tt class="xref py py-data docutils literal"><span class="pre">sys.float_info</span></tt></a>. Complex numbers have a real and imaginary part, which are each a floating point number. To extract these parts from a complex number <em>z</em>, use <tt class="docutils literal"><span class="pre">z.real</span></tt> and <tt class="docutils literal"><span class="pre">z.imag</span></tt>. (The standard library includes additional numeric types, <a class="reference internal" href="fractions.html#module-fractions" title="fractions: Rational numbers."><tt class="xref py py-mod docutils literal"><span class="pre">fractions</span></tt></a> that hold rationals, and <a class="reference internal" href="decimal.html#module-decimal" title="decimal: Implementation of the General Decimal Arithmetic Specification."><tt class="xref py py-mod docutils literal"><span class="pre">decimal</span></tt></a> that hold floating-point numbers with user-definable precision.)</p> <p id="index-14">Numbers are created by numeric literals or as the result of built-in functions and operators. Unadorned integer literals (including binary, hex, and octal numbers) yield plain integers unless the value they denote is too large to be represented as a plain integer, in which case they yield a long integer. Integer literals with an <tt class="docutils literal"><span class="pre">'L'</span></tt> or <tt class="docutils literal"><span class="pre">'l'</span></tt> suffix yield long integers (<tt class="docutils literal"><span class="pre">'L'</span></tt> is preferred because <tt class="docutils literal"><span class="pre">1l</span></tt> looks too much like eleven!). Numeric literals containing a decimal point or an exponent sign yield floating point numbers. Appending <tt class="docutils literal"><span class="pre">'j'</span></tt> or <tt class="docutils literal"><span class="pre">'J'</span></tt> to a numeric literal yields a complex number with a zero real part. A complex numeric literal is the sum of a real and an imaginary part.</p> <p id="index-15">Python fully supports mixed arithmetic: when a binary arithmetic operator has operands of different numeric types, the operand with the “narrower” type is widened to that of the other, where plain integer is narrower than long integer is narrower than floating point is narrower than complex. Comparisons between numbers of mixed type use the same rule. <a class="footnote-reference" href="#id13" id="id2">[2]</a> The constructors <a class="reference internal" href="functions.html#int" title="int"><tt class="xref py py-func docutils literal"><span class="pre">int()</span></tt></a>, <a class="reference internal" href="functions.html#long" title="long"><tt class="xref py py-func docutils literal"><span class="pre">long()</span></tt></a>, <a class="reference internal" href="functions.html#float" title="float"><tt class="xref py py-func docutils literal"><span class="pre">float()</span></tt></a>, and <a class="reference internal" href="functions.html#complex" title="complex"><tt class="xref py py-func docutils literal"><span class="pre">complex()</span></tt></a> can be used to produce numbers of a specific type.</p> <p>All built-in numeric types support the following operations. See <a class="reference internal" href="../reference/expressions.html#power"><em>The power operator</em></a> and later sections for the operators’ priorities.</p> <table border="1" class="docutils"> <colgroup> <col width="33%" /> <col width="54%" /> <col width="13%" /> </colgroup> <thead valign="bottom"> <tr class="row-odd"><th class="head">Operation</th> <th class="head">Result</th> <th class="head">Notes</th> </tr> </thead> <tbody valign="top"> <tr class="row-even"><td><tt class="docutils literal"><span class="pre">x</span> <span class="pre">+</span> <span class="pre">y</span></tt></td> <td>sum of <em>x</em> and <em>y</em></td> <td> </td> </tr> <tr class="row-odd"><td><tt class="docutils literal"><span class="pre">x</span> <span class="pre">-</span> <span class="pre">y</span></tt></td> <td>difference of <em>x</em> and <em>y</em></td> <td> </td> </tr> <tr class="row-even"><td><tt class="docutils literal"><span class="pre">x</span> <span class="pre">*</span> <span class="pre">y</span></tt></td> <td>product of <em>x</em> and <em>y</em></td> <td> </td> </tr> <tr class="row-odd"><td><tt class="docutils literal"><span class="pre">x</span> <span class="pre">/</span> <span class="pre">y</span></tt></td> <td>quotient of <em>x</em> and <em>y</em></td> <td>(1)</td> </tr> <tr class="row-even"><td><tt class="docutils literal"><span class="pre">x</span> <span class="pre">//</span> <span class="pre">y</span></tt></td> <td>(floored) quotient of <em>x</em> and <em>y</em></td> <td>(4)(5)</td> </tr> <tr class="row-odd"><td><tt class="docutils literal"><span class="pre">x</span> <span class="pre">%</span> <span class="pre">y</span></tt></td> <td>remainder of <tt class="docutils literal"><span class="pre">x</span> <span class="pre">/</span> <span class="pre">y</span></tt></td> <td>(4)</td> </tr> <tr class="row-even"><td><tt class="docutils literal"><span class="pre">-x</span></tt></td> <td><em>x</em> negated</td> <td> </td> </tr> <tr class="row-odd"><td><tt class="docutils literal"><span class="pre">+x</span></tt></td> <td><em>x</em> unchanged</td> <td> </td> </tr> <tr class="row-even"><td><tt class="docutils literal"><span class="pre">abs(x)</span></tt></td> <td>absolute value or magnitude of <em>x</em></td> <td>(3)</td> </tr> <tr class="row-odd"><td><tt class="docutils literal"><span class="pre">int(x)</span></tt></td> <td><em>x</em> converted to integer</td> <td>(2)</td> </tr> <tr class="row-even"><td><tt class="docutils literal"><span class="pre">long(x)</span></tt></td> <td><em>x</em> converted to long integer</td> <td>(2)</td> </tr> <tr class="row-odd"><td><tt class="docutils literal"><span class="pre">float(x)</span></tt></td> <td><em>x</em> converted to floating point</td> <td>(6)</td> </tr> <tr class="row-even"><td><tt class="docutils literal"><span class="pre">complex(re,im)</span></tt></td> <td>a complex number with real part <em>re</em>, imaginary part <em>im</em>. <em>im</em> defaults to zero.</td> <td> </td> </tr> <tr class="row-odd"><td><tt class="docutils literal"><span class="pre">c.conjugate()</span></tt></td> <td>conjugate of the complex number <em>c</em>. (Identity on real numbers)</td> <td> </td> </tr> <tr class="row-even"><td><tt class="docutils literal"><span class="pre">divmod(x,</span> <span class="pre">y)</span></tt></td> <td>the pair <tt class="docutils literal"><span class="pre">(x</span> <span class="pre">//</span> <span class="pre">y,</span> <span class="pre">x</span> <span class="pre">%</span> <span class="pre">y)</span></tt></td> <td>(3)(4)</td> </tr> <tr class="row-odd"><td><tt class="docutils literal"><span class="pre">pow(x,</span> <span class="pre">y)</span></tt></td> <td><em>x</em> to the power <em>y</em></td> <td>(3)(7)</td> </tr> <tr class="row-even"><td><tt class="docutils literal"><span class="pre">x</span> <span class="pre">**</span> <span class="pre">y</span></tt></td> <td><em>x</em> to the power <em>y</em></td> <td>(7)</td> </tr> </tbody> </table> <p id="index-16">Notes:</p> <ol class="arabic"> <li><p id="index-17">For (plain or long) integer division, the result is an integer. The result is always rounded towards minus infinity: 1/2 is 0, (-1)/2 is -1, 1/(-2) is -1, and (-1)/(-2) is 0. Note that the result is a long integer if either operand is a long integer, regardless of the numeric value.</p> </li> <li><p id="index-18">Conversion from floats using <a class="reference internal" href="functions.html#int" title="int"><tt class="xref py py-func docutils literal"><span class="pre">int()</span></tt></a> or <a class="reference internal" href="functions.html#long" title="long"><tt class="xref py py-func docutils literal"><span class="pre">long()</span></tt></a> truncates toward zero like the related function, <a class="reference internal" href="math.html#math.trunc" title="math.trunc"><tt class="xref py py-func docutils literal"><span class="pre">math.trunc()</span></tt></a>. Use the function <a class="reference internal" href="math.html#math.floor" title="math.floor"><tt class="xref py py-func docutils literal"><span class="pre">math.floor()</span></tt></a> to round downward and <a class="reference internal" href="math.html#math.ceil" title="math.ceil"><tt class="xref py py-func docutils literal"><span class="pre">math.ceil()</span></tt></a> to round upward.</p> </li> <li><p class="first">See <a class="reference internal" href="functions.html#built-in-funcs"><em>Built-in Functions</em></a> for a full description.</p> </li> <li><p class="first deprecated"> <span class="versionmodified">Deprecated since version 2.3: </span>The floor division operator, the modulo operator, and the <a class="reference internal" href="functions.html#divmod" title="divmod"><tt class="xref py py-func docutils literal"><span class="pre">divmod()</span></tt></a> function are no longer defined for complex numbers. Instead, convert to a floating point number using the <a class="reference internal" href="functions.html#abs" title="abs"><tt class="xref py py-func docutils literal"><span class="pre">abs()</span></tt></a> function if appropriate.</p> </li> <li><p class="first">Also referred to as integer division. The resultant value is a whole integer, though the result’s type is not necessarily int.</p> </li> <li><p class="first">float also accepts the strings “nan” and “inf” with an optional prefix “+” or “-” for Not a Number (NaN) and positive or negative infinity.</p> <p class="versionadded"> <span class="versionmodified">New in version 2.6.</span></p> </li> <li><p class="first">Python defines <tt class="docutils literal"><span class="pre">pow(0,</span> <span class="pre">0)</span></tt> and <tt class="docutils literal"><span class="pre">0</span> <span class="pre">**</span> <span class="pre">0</span></tt> to be <tt class="docutils literal"><span class="pre">1</span></tt>, as is common for programming languages.</p> </li> </ol> <p>All <a class="reference internal" href="numbers.html#numbers.Real" title="numbers.Real"><tt class="xref py py-class docutils literal"><span class="pre">numbers.Real</span></tt></a> types (<a class="reference internal" href="functions.html#int" title="int"><tt class="xref py py-class docutils literal"><span class="pre">int</span></tt></a>, <a class="reference internal" href="functions.html#long" title="long"><tt class="xref py py-class docutils literal"><span class="pre">long</span></tt></a>, and <a class="reference internal" href="functions.html#float" title="float"><tt class="xref py py-class docutils literal"><span class="pre">float</span></tt></a>) also include the following operations:</p> <table border="1" class="docutils"> <colgroup> <col width="31%" /> <col width="56%" /> <col width="13%" /> </colgroup> <thead valign="bottom"> <tr class="row-odd"><th class="head">Operation</th> <th class="head">Result</th> <th class="head">Notes</th> </tr> </thead> <tbody valign="top"> <tr class="row-even"><td><tt class="docutils literal"><span class="pre">math.trunc(x)</span></tt></td> <td><em>x</em> truncated to Integral</td> <td> </td> </tr> <tr class="row-odd"><td><tt class="docutils literal"><span class="pre">round(x[,</span> <span class="pre">n])</span></tt></td> <td><em>x</em> rounded to n digits, rounding half to even. If n is omitted, it defaults to 0.</td> <td> </td> </tr> <tr class="row-even"><td><tt class="docutils literal"><span class="pre">math.floor(x)</span></tt></td> <td>the greatest integral float <= <em>x</em></td> <td> </td> </tr> <tr class="row-odd"><td><tt class="docutils literal"><span class="pre">math.ceil(x)</span></tt></td> <td>the least integral float >= <em>x</em></td> <td> </td> </tr> </tbody> </table> <div class="section" id="bitwise-operations-on-integer-types"> <span id="bitstring-ops"></span><h3>5.4.1. Bitwise Operations on Integer Types<a class="headerlink" href="#bitwise-operations-on-integer-types" title="Permalink to this headline">¶</a></h3> <p id="index-19">Bitwise operations only make sense for integers. Negative numbers are treated as their 2’s complement value (this assumes a sufficiently large number of bits that no overflow occurs during the operation).</p> <p>The priorities of the binary bitwise operations are all lower than the numeric operations and higher than the comparisons; the unary operation <tt class="docutils literal"><span class="pre">~</span></tt> has the same priority as the other unary numeric operations (<tt class="docutils literal"><span class="pre">+</span></tt> and <tt class="docutils literal"><span class="pre">-</span></tt>).</p> <p>This table lists the bitwise operations sorted in ascending priority (operations in the same box have the same priority):</p> <table border="1" class="docutils"> <colgroup> <col width="22%" /> <col width="59%" /> <col width="19%" /> </colgroup> <thead valign="bottom"> <tr class="row-odd"><th class="head">Operation</th> <th class="head">Result</th> <th class="head">Notes</th> </tr> </thead> <tbody valign="top"> <tr class="row-even"><td><tt class="docutils literal"><span class="pre">x</span> <span class="pre">|</span> <span class="pre">y</span></tt></td> <td>bitwise <em class="dfn">or</em> of <em>x</em> and <em>y</em></td> <td> </td> </tr> <tr class="row-odd"><td><tt class="docutils literal"><span class="pre">x</span> <span class="pre">^</span> <span class="pre">y</span></tt></td> <td>bitwise <em class="dfn">exclusive or</em> of <em>x</em> and <em>y</em></td> <td> </td> </tr> <tr class="row-even"><td><tt class="docutils literal"><span class="pre">x</span> <span class="pre">&</span> <span class="pre">y</span></tt></td> <td>bitwise <em class="dfn">and</em> of <em>x</em> and <em>y</em></td> <td> </td> </tr> <tr class="row-odd"><td><tt class="docutils literal"><span class="pre">x</span> <span class="pre"><<</span> <span class="pre">n</span></tt></td> <td><em>x</em> shifted left by <em>n</em> bits</td> <td>(1)(2)</td> </tr> <tr class="row-even"><td><tt class="docutils literal"><span class="pre">x</span> <span class="pre">>></span> <span class="pre">n</span></tt></td> <td><em>x</em> shifted right by <em>n</em> bits</td> <td>(1)(3)</td> </tr> <tr class="row-odd"><td><tt class="docutils literal"><span class="pre">~x</span></tt></td> <td>the bits of <em>x</em> inverted</td> <td> </td> </tr> </tbody> </table> <p>Notes:</p> <ol class="arabic simple"> <li>Negative shift counts are illegal and cause a <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><tt class="xref py py-exc docutils literal"><span class="pre">ValueError</span></tt></a> to be raised.</li> <li>A left shift by <em>n</em> bits is equivalent to multiplication by <tt class="docutils literal"><span class="pre">pow(2,</span> <span class="pre">n)</span></tt>. A long integer is returned if the result exceeds the range of plain integers.</li> <li>A right shift by <em>n</em> bits is equivalent to division by <tt class="docutils literal"><span class="pre">pow(2,</span> <span class="pre">n)</span></tt>.</li> </ol> </div> <div class="section" id="additional-methods-on-integer-types"> <h3>5.4.2. Additional Methods on Integer Types<a class="headerlink" href="#additional-methods-on-integer-types" title="Permalink to this headline">¶</a></h3> <p>The integer types implement the <a class="reference internal" href="numbers.html#numbers.Integral" title="numbers.Integral"><tt class="xref py py-class docutils literal"><span class="pre">numbers.Integral</span></tt></a> <a class="reference internal" href="../glossary.html#term-abstract-base-class"><em class="xref std std-term">abstract base class</em></a>. In addition, they provide one more method:</p> <dl class="method"> <dt id="int.bit_length"> <tt class="descclassname">int.</tt><tt class="descname">bit_length</tt><big>(</big><big>)</big><a class="headerlink" href="#int.bit_length" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="method"> <dt id="long.bit_length"> <tt class="descclassname">long.</tt><tt class="descname">bit_length</tt><big>(</big><big>)</big><a class="headerlink" href="#long.bit_length" title="Permalink to this definition">¶</a></dt> <dd><p>Return the number of bits necessary to represent an integer in binary, excluding the sign and leading zeros:</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">n</span> <span class="o">=</span> <span class="o">-</span><span class="mi">37</span> <span class="gp">>>> </span><span class="nb">bin</span><span class="p">(</span><span class="n">n</span><span class="p">)</span> <span class="go">'-0b100101'</span> <span class="gp">>>> </span><span class="n">n</span><span class="o">.</span><span class="n">bit_length</span><span class="p">()</span> <span class="go">6</span> </pre></div> </div> <p>More precisely, if <tt class="docutils literal"><span class="pre">x</span></tt> is nonzero, then <tt class="docutils literal"><span class="pre">x.bit_length()</span></tt> is the unique positive integer <tt class="docutils literal"><span class="pre">k</span></tt> such that <tt class="docutils literal"><span class="pre">2**(k-1)</span> <span class="pre"><=</span> <span class="pre">abs(x)</span> <span class="pre"><</span> <span class="pre">2**k</span></tt>. Equivalently, when <tt class="docutils literal"><span class="pre">abs(x)</span></tt> is small enough to have a correctly rounded logarithm, then <tt class="docutils literal"><span class="pre">k</span> <span class="pre">=</span> <span class="pre">1</span> <span class="pre">+</span> <span class="pre">int(log(abs(x),</span> <span class="pre">2))</span></tt>. If <tt class="docutils literal"><span class="pre">x</span></tt> is zero, then <tt class="docutils literal"><span class="pre">x.bit_length()</span></tt> returns <tt class="docutils literal"><span class="pre">0</span></tt>.</p> <p>Equivalent to:</p> <div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">bit_length</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="n">s</span> <span class="o">=</span> <span class="nb">bin</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span> <span class="c"># binary representation: bin(-37) --> '-0b100101'</span> <span class="n">s</span> <span class="o">=</span> <span class="n">s</span><span class="o">.</span><span class="n">lstrip</span><span class="p">(</span><span class="s">'-0b'</span><span class="p">)</span> <span class="c"># remove leading zeros and minus sign</span> <span class="k">return</span> <span class="nb">len</span><span class="p">(</span><span class="n">s</span><span class="p">)</span> <span class="c"># len('100101') --> 6</span> </pre></div> </div> <p class="versionadded"> <span class="versionmodified">New in version 2.7.</span></p> </dd></dl> </div> <div class="section" id="additional-methods-on-float"> <h3>5.4.3. Additional Methods on Float<a class="headerlink" href="#additional-methods-on-float" title="Permalink to this headline">¶</a></h3> <p>The float type implements the <a class="reference internal" href="numbers.html#numbers.Real" title="numbers.Real"><tt class="xref py py-class docutils literal"><span class="pre">numbers.Real</span></tt></a> <a class="reference internal" href="../glossary.html#term-abstract-base-class"><em class="xref std std-term">abstract base class</em></a>. float also has the following additional methods.</p> <dl class="method"> <dt id="float.as_integer_ratio"> <tt class="descclassname">float.</tt><tt class="descname">as_integer_ratio</tt><big>(</big><big>)</big><a class="headerlink" href="#float.as_integer_ratio" title="Permalink to this definition">¶</a></dt> <dd><p>Return a pair of integers whose ratio is exactly equal to the original float and with a positive denominator. Raises <a class="reference internal" href="exceptions.html#exceptions.OverflowError" title="exceptions.OverflowError"><tt class="xref py py-exc docutils literal"><span class="pre">OverflowError</span></tt></a> on infinities and a <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><tt class="xref py py-exc docutils literal"><span class="pre">ValueError</span></tt></a> on NaNs.</p> <p class="versionadded"> <span class="versionmodified">New in version 2.6.</span></p> </dd></dl> <dl class="method"> <dt id="float.is_integer"> <tt class="descclassname">float.</tt><tt class="descname">is_integer</tt><big>(</big><big>)</big><a class="headerlink" href="#float.is_integer" title="Permalink to this definition">¶</a></dt> <dd><p>Return <tt class="docutils literal"><span class="pre">True</span></tt> if the float instance is finite with integral value, and <tt class="docutils literal"><span class="pre">False</span></tt> otherwise:</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="p">(</span><span class="o">-</span><span class="mf">2.0</span><span class="p">)</span><span class="o">.</span><span class="n">is_integer</span><span class="p">()</span> <span class="go">True</span> <span class="gp">>>> </span><span class="p">(</span><span class="mf">3.2</span><span class="p">)</span><span class="o">.</span><span class="n">is_integer</span><span class="p">()</span> <span class="go">False</span> </pre></div> </div> <p class="versionadded"> <span class="versionmodified">New in version 2.6.</span></p> </dd></dl> <p>Two methods support conversion to and from hexadecimal strings. Since Python’s floats are stored internally as binary numbers, converting a float to or from a <em>decimal</em> string usually involves a small rounding error. In contrast, hexadecimal strings allow exact representation and specification of floating-point numbers. This can be useful when debugging, and in numerical work.</p> <dl class="method"> <dt id="float.hex"> <tt class="descclassname">float.</tt><tt class="descname">hex</tt><big>(</big><big>)</big><a class="headerlink" href="#float.hex" title="Permalink to this definition">¶</a></dt> <dd><p>Return a representation of a floating-point number as a hexadecimal string. For finite floating-point numbers, this representation will always include a leading <tt class="docutils literal"><span class="pre">0x</span></tt> and a trailing <tt class="docutils literal"><span class="pre">p</span></tt> and exponent.</p> <p class="versionadded"> <span class="versionmodified">New in version 2.6.</span></p> </dd></dl> <dl class="method"> <dt id="float.fromhex"> <tt class="descclassname">float.</tt><tt class="descname">fromhex</tt><big>(</big><em>s</em><big>)</big><a class="headerlink" href="#float.fromhex" title="Permalink to this definition">¶</a></dt> <dd><p>Class method to return the float represented by a hexadecimal string <em>s</em>. The string <em>s</em> may have leading and trailing whitespace.</p> <p class="versionadded"> <span class="versionmodified">New in version 2.6.</span></p> </dd></dl> <p>Note that <a class="reference internal" href="#float.hex" title="float.hex"><tt class="xref py py-meth docutils literal"><span class="pre">float.hex()</span></tt></a> is an instance method, while <a class="reference internal" href="#float.fromhex" title="float.fromhex"><tt class="xref py py-meth docutils literal"><span class="pre">float.fromhex()</span></tt></a> is a class method.</p> <p>A hexadecimal string takes the form:</p> <div class="highlight-python"><pre>[sign] ['0x'] integer ['.' fraction] ['p' exponent]</pre> </div> <p>where the optional <tt class="docutils literal"><span class="pre">sign</span></tt> may by either <tt class="docutils literal"><span class="pre">+</span></tt> or <tt class="docutils literal"><span class="pre">-</span></tt>, <tt class="docutils literal"><span class="pre">integer</span></tt> and <tt class="docutils literal"><span class="pre">fraction</span></tt> are strings of hexadecimal digits, and <tt class="docutils literal"><span class="pre">exponent</span></tt> is a decimal integer with an optional leading sign. Case is not significant, and there must be at least one hexadecimal digit in either the integer or the fraction. This syntax is similar to the syntax specified in section 6.4.4.2 of the C99 standard, and also to the syntax used in Java 1.5 onwards. In particular, the output of <a class="reference internal" href="#float.hex" title="float.hex"><tt class="xref py py-meth docutils literal"><span class="pre">float.hex()</span></tt></a> is usable as a hexadecimal floating-point literal in C or Java code, and hexadecimal strings produced by C’s <tt class="docutils literal"><span class="pre">%a</span></tt> format character or Java’s <tt class="docutils literal"><span class="pre">Double.toHexString</span></tt> are accepted by <a class="reference internal" href="#float.fromhex" title="float.fromhex"><tt class="xref py py-meth docutils literal"><span class="pre">float.fromhex()</span></tt></a>.</p> <p>Note that the exponent is written in decimal rather than hexadecimal, and that it gives the power of 2 by which to multiply the coefficient. For example, the hexadecimal string <tt class="docutils literal"><span class="pre">0x3.a7p10</span></tt> represents the floating-point number <tt class="docutils literal"><span class="pre">(3</span> <span class="pre">+</span> <span class="pre">10./16</span> <span class="pre">+</span> <span class="pre">7./16**2)</span> <span class="pre">*</span> <span class="pre">2.0**10</span></tt>, or <tt class="docutils literal"><span class="pre">3740.0</span></tt>:</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="nb">float</span><span class="o">.</span><span class="n">fromhex</span><span class="p">(</span><span class="s">'0x3.a7p10'</span><span class="p">)</span> <span class="go">3740.0</span> </pre></div> </div> <p>Applying the reverse conversion to <tt class="docutils literal"><span class="pre">3740.0</span></tt> gives a different hexadecimal string representing the same number:</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="nb">float</span><span class="o">.</span><span class="n">hex</span><span class="p">(</span><span class="mf">3740.0</span><span class="p">)</span> <span class="go">'0x1.d380000000000p+11'</span> </pre></div> </div> </div> </div> <div class="section" id="iterator-types"> <span id="typeiter"></span><h2>5.5. Iterator Types<a class="headerlink" href="#iterator-types" title="Permalink to this headline">¶</a></h2> <p class="versionadded"> <span class="versionmodified">New in version 2.2.</span></p> <p id="index-20">Python supports a concept of iteration over containers. This is implemented using two distinct methods; these are used to allow user-defined classes to support iteration. Sequences, described below in more detail, always support the iteration methods.</p> <p>One method needs to be defined for container objects to provide iteration support:</p> <dl class="method"> <dt id="container.__iter__"> <tt class="descclassname">container.</tt><tt class="descname">__iter__</tt><big>(</big><big>)</big><a class="headerlink" href="#container.__iter__" title="Permalink to this definition">¶</a></dt> <dd><p>Return an iterator object. The object is required to support the iterator protocol described below. If a container supports different types of iteration, additional methods can be provided to specifically request iterators for those iteration types. (An example of an object supporting multiple forms of iteration would be a tree structure which supports both breadth-first and depth-first traversal.) This method corresponds to the <tt class="xref py py-attr docutils literal"><span class="pre">tp_iter</span></tt> slot of the type structure for Python objects in the Python/C API.</p> </dd></dl> <p>The iterator objects themselves are required to support the following two methods, which together form the <em class="dfn">iterator protocol</em>:</p> <dl class="method"> <dt id="iterator.__iter__"> <tt class="descclassname">iterator.</tt><tt class="descname">__iter__</tt><big>(</big><big>)</big><a class="headerlink" href="#iterator.__iter__" title="Permalink to this definition">¶</a></dt> <dd><p>Return the iterator object itself. This is required to allow both containers and iterators to be used with the <a class="reference internal" href="../reference/compound_stmts.html#for"><tt class="xref std std-keyword docutils literal"><span class="pre">for</span></tt></a> and <a class="reference internal" href="../reference/expressions.html#in"><tt class="xref std std-keyword docutils literal"><span class="pre">in</span></tt></a> statements. This method corresponds to the <tt class="xref py py-attr docutils literal"><span class="pre">tp_iter</span></tt> slot of the type structure for Python objects in the Python/C API.</p> </dd></dl> <dl class="method"> <dt id="iterator.next"> <tt class="descclassname">iterator.</tt><tt class="descname">next</tt><big>(</big><big>)</big><a class="headerlink" href="#iterator.next" title="Permalink to this definition">¶</a></dt> <dd><p>Return the next item from the container. If there are no further items, raise the <a class="reference internal" href="exceptions.html#exceptions.StopIteration" title="exceptions.StopIteration"><tt class="xref py py-exc docutils literal"><span class="pre">StopIteration</span></tt></a> exception. This method corresponds to the <tt class="xref py py-attr docutils literal"><span class="pre">tp_iternext</span></tt> slot of the type structure for Python objects in the Python/C API.</p> </dd></dl> <p>Python defines several iterator objects to support iteration over general and specific sequence types, dictionaries, and other more specialized forms. The specific types are not important beyond their implementation of the iterator protocol.</p> <p>The intention of the protocol is that once an iterator’s <a class="reference internal" href="functions.html#next" title="next"><tt class="xref py py-meth docutils literal"><span class="pre">next()</span></tt></a> method raises <a class="reference internal" href="exceptions.html#exceptions.StopIteration" title="exceptions.StopIteration"><tt class="xref py py-exc docutils literal"><span class="pre">StopIteration</span></tt></a>, it will continue to do so on subsequent calls. Implementations that do not obey this property are deemed broken. (This constraint was added in Python 2.3; in Python 2.2, various iterators are broken according to this rule.)</p> <div class="section" id="generator-types"> <span id="id3"></span><h3>5.5.1. Generator Types<a class="headerlink" href="#generator-types" title="Permalink to this headline">¶</a></h3> <p>Python’s <a class="reference internal" href="../glossary.html#term-generator"><em class="xref std std-term">generator</em></a>s provide a convenient way to implement the iterator protocol. If a container object’s <a class="reference internal" href="../reference/datamodel.html#object.__iter__" title="object.__iter__"><tt class="xref py py-meth docutils literal"><span class="pre">__iter__()</span></tt></a> method is implemented as a generator, it will automatically return an iterator object (technically, a generator object) supplying the <a class="reference internal" href="../reference/datamodel.html#object.__iter__" title="object.__iter__"><tt class="xref py py-meth docutils literal"><span class="pre">__iter__()</span></tt></a> and <a class="reference internal" href="functions.html#next" title="next"><tt class="xref py py-meth docutils literal"><span class="pre">next()</span></tt></a> methods. More information about generators can be found in <a class="reference internal" href="../reference/expressions.html#yieldexpr"><em>the documentation for the yield expression</em></a>.</p> </div> </div> <div class="section" id="sequence-types-str-unicode-list-tuple-bytearray-buffer-xrange"> <span id="typesseq"></span><h2>5.6. Sequence Types — <a class="reference internal" href="functions.html#str" title="str"><tt class="xref py py-class docutils literal"><span class="pre">str</span></tt></a>, <a class="reference internal" href="functions.html#unicode" title="unicode"><tt class="xref py py-class docutils literal"><span class="pre">unicode</span></tt></a>, <a class="reference internal" href="functions.html#list" title="list"><tt class="xref py py-class docutils literal"><span class="pre">list</span></tt></a>, <a class="reference internal" href="functions.html#tuple" title="tuple"><tt class="xref py py-class docutils literal"><span class="pre">tuple</span></tt></a>, <a class="reference internal" href="functions.html#bytearray" title="bytearray"><tt class="xref py py-class docutils literal"><span class="pre">bytearray</span></tt></a>, <a class="reference internal" href="functions.html#buffer" title="buffer"><tt class="xref py py-class docutils literal"><span class="pre">buffer</span></tt></a>, <a class="reference internal" href="functions.html#xrange" title="xrange"><tt class="xref py py-class docutils literal"><span class="pre">xrange</span></tt></a><a class="headerlink" href="#sequence-types-str-unicode-list-tuple-bytearray-buffer-xrange" title="Permalink to this headline">¶</a></h2> <p>There are seven sequence types: strings, Unicode strings, lists, tuples, bytearrays, buffers, and xrange objects.</p> <p>For other containers see the built in <a class="reference internal" href="#dict" title="dict"><tt class="xref py py-class docutils literal"><span class="pre">dict</span></tt></a> and <a class="reference internal" href="#set" title="set"><tt class="xref py py-class docutils literal"><span class="pre">set</span></tt></a> classes, and the <a class="reference internal" href="collections.html#module-collections" title="collections: High-performance datatypes"><tt class="xref py py-mod docutils literal"><span class="pre">collections</span></tt></a> module.</p> <p id="index-21">String literals are written in single or double quotes: <tt class="docutils literal"><span class="pre">'xyzzy'</span></tt>, <tt class="docutils literal"><span class="pre">"frobozz"</span></tt>. See <a class="reference internal" href="../reference/lexical_analysis.html#strings"><em>String literals</em></a> for more about string literals. Unicode strings are much like strings, but are specified in the syntax using a preceding <tt class="docutils literal"><span class="pre">'u'</span></tt> character: <tt class="docutils literal"><span class="pre">u'abc'</span></tt>, <tt class="docutils literal"><span class="pre">u"def"</span></tt>. In addition to the functionality described here, there are also string-specific methods described in the <a class="reference internal" href="#string-methods"><em>String Methods</em></a> section. Lists are constructed with square brackets, separating items with commas: <tt class="docutils literal"><span class="pre">[a,</span> <span class="pre">b,</span> <span class="pre">c]</span></tt>. Tuples are constructed by the comma operator (not within square brackets), with or without enclosing parentheses, but an empty tuple must have the enclosing parentheses, such as <tt class="docutils literal"><span class="pre">a,</span> <span class="pre">b,</span> <span class="pre">c</span></tt> or <tt class="docutils literal"><span class="pre">()</span></tt>. A single item tuple must have a trailing comma, such as <tt class="docutils literal"><span class="pre">(d,)</span></tt>.</p> <p>Bytearray objects are created with the built-in function <a class="reference internal" href="functions.html#bytearray" title="bytearray"><tt class="xref py py-func docutils literal"><span class="pre">bytearray()</span></tt></a>.</p> <p>Buffer objects are not directly supported by Python syntax, but can be created by calling the built-in function <a class="reference internal" href="functions.html#buffer" title="buffer"><tt class="xref py py-func docutils literal"><span class="pre">buffer()</span></tt></a>. They don’t support concatenation or repetition.</p> <p>Objects of type xrange are similar to buffers in that there is no specific syntax to create them, but they are created using the <a class="reference internal" href="functions.html#xrange" title="xrange"><tt class="xref py py-func docutils literal"><span class="pre">xrange()</span></tt></a> function. They don’t support slicing, concatenation or repetition, and using <tt class="docutils literal"><span class="pre">in</span></tt>, <tt class="docutils literal"><span class="pre">not</span> <span class="pre">in</span></tt>, <a class="reference internal" href="functions.html#min" title="min"><tt class="xref py py-func docutils literal"><span class="pre">min()</span></tt></a> or <a class="reference internal" href="functions.html#max" title="max"><tt class="xref py py-func docutils literal"><span class="pre">max()</span></tt></a> on them is inefficient.</p> <p>Most sequence types support the following operations. The <tt class="docutils literal"><span class="pre">in</span></tt> and <tt class="docutils literal"><span class="pre">not</span> <span class="pre">in</span></tt> operations have the same priorities as the comparison operations. The <tt class="docutils literal"><span class="pre">+</span></tt> and <tt class="docutils literal"><span class="pre">*</span></tt> operations have the same priority as the corresponding numeric operations. <a class="footnote-reference" href="#id14" id="id4">[3]</a> Additional methods are provided for <a class="reference internal" href="#typesseq-mutable"><em>Mutable Sequence Types</em></a>.</p> <p>This table lists the sequence operations sorted in ascending priority (operations in the same box have the same priority). In the table, <em>s</em> and <em>t</em> are sequences of the same type; <em>n</em>, <em>i</em> and <em>j</em> are integers:</p> <table border="1" class="docutils"> <colgroup> <col width="30%" /> <col width="53%" /> <col width="17%" /> </colgroup> <thead valign="bottom"> <tr class="row-odd"><th class="head">Operation</th> <th class="head">Result</th> <th class="head">Notes</th> </tr> </thead> <tbody valign="top"> <tr class="row-even"><td><tt class="docutils literal"><span class="pre">x</span> <span class="pre">in</span> <span class="pre">s</span></tt></td> <td><tt class="docutils literal"><span class="pre">True</span></tt> if an item of <em>s</em> is equal to <em>x</em>, else <tt class="docutils literal"><span class="pre">False</span></tt></td> <td>(1)</td> </tr> <tr class="row-odd"><td><tt class="docutils literal"><span class="pre">x</span> <span class="pre">not</span> <span class="pre">in</span> <span class="pre">s</span></tt></td> <td><tt class="docutils literal"><span class="pre">False</span></tt> if an item of <em>s</em> is equal to <em>x</em>, else <tt class="docutils literal"><span class="pre">True</span></tt></td> <td>(1)</td> </tr> <tr class="row-even"><td><tt class="docutils literal"><span class="pre">s</span> <span class="pre">+</span> <span class="pre">t</span></tt></td> <td>the concatenation of <em>s</em> and <em>t</em></td> <td>(6)</td> </tr> <tr class="row-odd"><td><tt class="docutils literal"><span class="pre">s</span> <span class="pre">*</span> <span class="pre">n,</span> <span class="pre">n</span> <span class="pre">*</span> <span class="pre">s</span></tt></td> <td><em>n</em> shallow copies of <em>s</em> concatenated</td> <td>(2)</td> </tr> <tr class="row-even"><td><tt class="docutils literal"><span class="pre">s[i]</span></tt></td> <td><em>i</em>th item of <em>s</em>, origin 0</td> <td>(3)</td> </tr> <tr class="row-odd"><td><tt class="docutils literal"><span class="pre">s[i:j]</span></tt></td> <td>slice of <em>s</em> from <em>i</em> to <em>j</em></td> <td>(3)(4)</td> </tr> <tr class="row-even"><td><tt class="docutils literal"><span class="pre">s[i:j:k]</span></tt></td> <td>slice of <em>s</em> from <em>i</em> to <em>j</em> with step <em>k</em></td> <td>(3)(5)</td> </tr> <tr class="row-odd"><td><tt class="docutils literal"><span class="pre">len(s)</span></tt></td> <td>length of <em>s</em></td> <td> </td> </tr> <tr class="row-even"><td><tt class="docutils literal"><span class="pre">min(s)</span></tt></td> <td>smallest item of <em>s</em></td> <td> </td> </tr> <tr class="row-odd"><td><tt class="docutils literal"><span class="pre">max(s)</span></tt></td> <td>largest item of <em>s</em></td> <td> </td> </tr> <tr class="row-even"><td><tt class="docutils literal"><span class="pre">s.index(i)</span></tt></td> <td>index of the first occurence of <em>i</em> in <em>s</em></td> <td> </td> </tr> <tr class="row-odd"><td><tt class="docutils literal"><span class="pre">s.count(i)</span></tt></td> <td>total number of occurences of <em>i</em> in <em>s</em></td> <td> </td> </tr> </tbody> </table> <p>Sequence types also support comparisons. In particular, tuples and lists are compared lexicographically by comparing corresponding elements. This means that to compare equal, every element must compare equal and the two sequences must be of the same type and have the same length. (For full details see <a class="reference internal" href="../reference/expressions.html#comparisons"><em>Comparisons</em></a> in the language reference.)</p> <p id="index-22">Notes:</p> <ol class="arabic"> <li><p class="first">When <em>s</em> is a string or Unicode string object the <tt class="docutils literal"><span class="pre">in</span></tt> and <tt class="docutils literal"><span class="pre">not</span> <span class="pre">in</span></tt> operations act like a substring test. In Python versions before 2.3, <em>x</em> had to be a string of length 1. In Python 2.3 and beyond, <em>x</em> may be a string of any length.</p> </li> <li><p class="first">Values of <em>n</em> less than <tt class="docutils literal"><span class="pre">0</span></tt> are treated as <tt class="docutils literal"><span class="pre">0</span></tt> (which yields an empty sequence of the same type as <em>s</em>). Note also that the copies are shallow; nested structures are not copied. This often haunts new Python programmers; consider:</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">lists</span> <span class="o">=</span> <span class="p">[[]]</span> <span class="o">*</span> <span class="mi">3</span> <span class="gp">>>> </span><span class="n">lists</span> <span class="go">[[], [], []]</span> <span class="gp">>>> </span><span class="n">lists</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">lists</span> <span class="go">[[3], [3], [3]]</span> </pre></div> </div> <p>What has happened is that <tt class="docutils literal"><span class="pre">[[]]</span></tt> is a one-element list containing an empty list, so all three elements of <tt class="docutils literal"><span class="pre">[[]]</span> <span class="pre">*</span> <span class="pre">3</span></tt> are (pointers to) this single empty list. Modifying any of the elements of <tt class="docutils literal"><span class="pre">lists</span></tt> modifies this single list. You can create a list of different lists this way:</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">lists</span> <span class="o">=</span> <span class="p">[[]</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">3</span><span class="p">)]</span> <span class="gp">>>> </span><span class="n">lists</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">lists</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="mi">5</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">lists</span><span class="p">[</span><span class="mi">2</span><span class="p">]</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="mi">7</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">lists</span> <span class="go">[[3], [5], [7]]</span> </pre></div> </div> </li> <li><p class="first">If <em>i</em> or <em>j</em> is negative, the index is relative to the end of the string: <tt class="docutils literal"><span class="pre">len(s)</span> <span class="pre">+</span> <span class="pre">i</span></tt> or <tt class="docutils literal"><span class="pre">len(s)</span> <span class="pre">+</span> <span class="pre">j</span></tt> is substituted. But note that <tt class="docutils literal"><span class="pre">-0</span></tt> is still <tt class="docutils literal"><span class="pre">0</span></tt>.</p> </li> <li><p class="first">The slice of <em>s</em> from <em>i</em> to <em>j</em> is defined as the sequence of items with index <em>k</em> such that <tt class="docutils literal"><span class="pre">i</span> <span class="pre"><=</span> <span class="pre">k</span> <span class="pre"><</span> <span class="pre">j</span></tt>. If <em>i</em> or <em>j</em> is greater than <tt class="docutils literal"><span class="pre">len(s)</span></tt>, use <tt class="docutils literal"><span class="pre">len(s)</span></tt>. If <em>i</em> is omitted or <tt class="docutils literal"><span class="pre">None</span></tt>, use <tt class="docutils literal"><span class="pre">0</span></tt>. If <em>j</em> is omitted or <tt class="docutils literal"><span class="pre">None</span></tt>, use <tt class="docutils literal"><span class="pre">len(s)</span></tt>. If <em>i</em> is greater than or equal to <em>j</em>, the slice is empty.</p> </li> <li><p class="first">The slice of <em>s</em> from <em>i</em> to <em>j</em> with step <em>k</em> is defined as the sequence of items with index <tt class="docutils literal"><span class="pre">x</span> <span class="pre">=</span> <span class="pre">i</span> <span class="pre">+</span> <span class="pre">n*k</span></tt> such that <tt class="docutils literal"><span class="pre">0</span> <span class="pre"><=</span> <span class="pre">n</span> <span class="pre"><</span> <span class="pre">(j-i)/k</span></tt>. In other words, the indices are <tt class="docutils literal"><span class="pre">i</span></tt>, <tt class="docutils literal"><span class="pre">i+k</span></tt>, <tt class="docutils literal"><span class="pre">i+2*k</span></tt>, <tt class="docutils literal"><span class="pre">i+3*k</span></tt> and so on, stopping when <em>j</em> is reached (but never including <em>j</em>). If <em>i</em> or <em>j</em> is greater than <tt class="docutils literal"><span class="pre">len(s)</span></tt>, use <tt class="docutils literal"><span class="pre">len(s)</span></tt>. If <em>i</em> or <em>j</em> are omitted or <tt class="docutils literal"><span class="pre">None</span></tt>, they become “end” values (which end depends on the sign of <em>k</em>). Note, <em>k</em> cannot be zero. If <em>k</em> is <tt class="docutils literal"><span class="pre">None</span></tt>, it is treated like <tt class="docutils literal"><span class="pre">1</span></tt>.</p> </li> <li><div class="impl-detail first compound"> <p><strong>CPython implementation detail:</strong> If <em>s</em> and <em>t</em> are both strings, some Python implementations such as CPython can usually perform an in-place optimization for assignments of the form <tt class="docutils literal"><span class="pre">s</span> <span class="pre">=</span> <span class="pre">s</span> <span class="pre">+</span> <span class="pre">t</span></tt> or <tt class="docutils literal"><span class="pre">s</span> <span class="pre">+=</span> <span class="pre">t</span></tt>. When applicable, this optimization makes quadratic run-time much less likely. This optimization is both version and implementation dependent. For performance sensitive code, it is preferable to use the <a class="reference internal" href="#str.join" title="str.join"><tt class="xref py py-meth docutils literal"><span class="pre">str.join()</span></tt></a> method which assures consistent linear concatenation performance across versions and implementations.</p> </div> <p class="versionchanged"> <span class="versionmodified">Changed in version 2.4: </span>Formerly, string concatenation never occurred in-place.</p> </li> </ol> <div class="section" id="string-methods"> <span id="id5"></span><h3>5.6.1. String Methods<a class="headerlink" href="#string-methods" title="Permalink to this headline">¶</a></h3> <p id="index-23">Below are listed the string methods which both 8-bit strings and Unicode objects support. Some of them are also available on <a class="reference internal" href="functions.html#bytearray" title="bytearray"><tt class="xref py py-class docutils literal"><span class="pre">bytearray</span></tt></a> objects.</p> <p>In addition, Python’s strings support the sequence type methods described in the <a class="reference internal" href="#typesseq"><em>Sequence Types — str, unicode, list, tuple, bytearray, buffer, xrange</em></a> section. To output formatted strings use template strings or the <tt class="docutils literal"><span class="pre">%</span></tt> operator described in the <a class="reference internal" href="#string-formatting"><em>String Formatting Operations</em></a> section. Also, see the <a class="reference internal" href="re.html#module-re" title="re: Regular expression operations."><tt class="xref py py-mod docutils literal"><span class="pre">re</span></tt></a> module for string functions based on regular expressions.</p> <dl class="method"> <dt id="str.capitalize"> <tt class="descclassname">str.</tt><tt class="descname">capitalize</tt><big>(</big><big>)</big><a class="headerlink" href="#str.capitalize" title="Permalink to this definition">¶</a></dt> <dd><p>Return a copy of the string with its first character capitalized and the rest lowercased.</p> <p>For 8-bit strings, this method is locale-dependent.</p> </dd></dl> <dl class="method"> <dt id="str.center"> <tt class="descclassname">str.</tt><tt class="descname">center</tt><big>(</big><em>width</em><span class="optional">[</span>, <em>fillchar</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#str.center" title="Permalink to this definition">¶</a></dt> <dd><p>Return centered in a string of length <em>width</em>. Padding is done using the specified <em>fillchar</em> (default is a space).</p> <p class="versionchanged"> <span class="versionmodified">Changed in version 2.4: </span>Support for the <em>fillchar</em> argument.</p> </dd></dl> <dl class="method"> <dt id="str.count"> <tt class="descclassname">str.</tt><tt class="descname">count</tt><big>(</big><em>sub</em><span class="optional">[</span>, <em>start</em><span class="optional">[</span>, <em>end</em><span class="optional">]</span><span class="optional">]</span><big>)</big><a class="headerlink" href="#str.count" title="Permalink to this definition">¶</a></dt> <dd><p>Return the number of non-overlapping occurrences of substring <em>sub</em> in the range [<em>start</em>, <em>end</em>]. Optional arguments <em>start</em> and <em>end</em> are interpreted as in slice notation.</p> </dd></dl> <dl class="method"> <dt id="str.decode"> <tt class="descclassname">str.</tt><tt class="descname">decode</tt><big>(</big><span class="optional">[</span><em>encoding</em><span class="optional">[</span>, <em>errors</em><span class="optional">]</span><span class="optional">]</span><big>)</big><a class="headerlink" href="#str.decode" title="Permalink to this definition">¶</a></dt> <dd><p>Decodes the string using the codec registered for <em>encoding</em>. <em>encoding</em> defaults to the default string encoding. <em>errors</em> may be given to set a different error handling scheme. The default is <tt class="docutils literal"><span class="pre">'strict'</span></tt>, meaning that encoding errors raise <a class="reference internal" href="exceptions.html#exceptions.UnicodeError" title="exceptions.UnicodeError"><tt class="xref py py-exc docutils literal"><span class="pre">UnicodeError</span></tt></a>. Other possible values are <tt class="docutils literal"><span class="pre">'ignore'</span></tt>, <tt class="docutils literal"><span class="pre">'replace'</span></tt> and any other name registered via <a class="reference internal" href="codecs.html#codecs.register_error" title="codecs.register_error"><tt class="xref py py-func docutils literal"><span class="pre">codecs.register_error()</span></tt></a>, see section <a class="reference internal" href="codecs.html#codec-base-classes"><em>Codec Base Classes</em></a>.</p> <p class="versionadded"> <span class="versionmodified">New in version 2.2.</span></p> <p class="versionchanged"> <span class="versionmodified">Changed in version 2.3: </span>Support for other error handling schemes added.</p> <p class="versionchanged"> <span class="versionmodified">Changed in version 2.7: </span>Support for keyword arguments added.</p> </dd></dl> <dl class="method"> <dt id="str.encode"> <tt class="descclassname">str.</tt><tt class="descname">encode</tt><big>(</big><span class="optional">[</span><em>encoding</em><span class="optional">[</span>, <em>errors</em><span class="optional">]</span><span class="optional">]</span><big>)</big><a class="headerlink" href="#str.encode" title="Permalink to this definition">¶</a></dt> <dd><p>Return an encoded version of the string. Default encoding is the current default string encoding. <em>errors</em> may be given to set a different error handling scheme. The default for <em>errors</em> is <tt class="docutils literal"><span class="pre">'strict'</span></tt>, meaning that encoding errors raise a <a class="reference internal" href="exceptions.html#exceptions.UnicodeError" title="exceptions.UnicodeError"><tt class="xref py py-exc docutils literal"><span class="pre">UnicodeError</span></tt></a>. Other possible values are <tt class="docutils literal"><span class="pre">'ignore'</span></tt>, <tt class="docutils literal"><span class="pre">'replace'</span></tt>, <tt class="docutils literal"><span class="pre">'xmlcharrefreplace'</span></tt>, <tt class="docutils literal"><span class="pre">'backslashreplace'</span></tt> and any other name registered via <a class="reference internal" href="codecs.html#codecs.register_error" title="codecs.register_error"><tt class="xref py py-func docutils literal"><span class="pre">codecs.register_error()</span></tt></a>, see section <a class="reference internal" href="codecs.html#codec-base-classes"><em>Codec Base Classes</em></a>. For a list of possible encodings, see section <a class="reference internal" href="codecs.html#standard-encodings"><em>Standard Encodings</em></a>.</p> <p class="versionadded"> <span class="versionmodified">New in version 2.0.</span></p> <p class="versionchanged"> <span class="versionmodified">Changed in version 2.3: </span>Support for <tt class="docutils literal"><span class="pre">'xmlcharrefreplace'</span></tt> and <tt class="docutils literal"><span class="pre">'backslashreplace'</span></tt> and other error handling schemes added.</p> <p class="versionchanged"> <span class="versionmodified">Changed in version 2.7: </span>Support for keyword arguments added.</p> </dd></dl> <dl class="method"> <dt id="str.endswith"> <tt class="descclassname">str.</tt><tt class="descname">endswith</tt><big>(</big><em>suffix</em><span class="optional">[</span>, <em>start</em><span class="optional">[</span>, <em>end</em><span class="optional">]</span><span class="optional">]</span><big>)</big><a class="headerlink" href="#str.endswith" title="Permalink to this definition">¶</a></dt> <dd><p>Return <tt class="docutils literal"><span class="pre">True</span></tt> if the string ends with the specified <em>suffix</em>, otherwise return <tt class="docutils literal"><span class="pre">False</span></tt>. <em>suffix</em> can also be a tuple of suffixes to look for. With optional <em>start</em>, test beginning at that position. With optional <em>end</em>, stop comparing at that position.</p> <p class="versionchanged"> <span class="versionmodified">Changed in version 2.5: </span>Accept tuples as <em>suffix</em>.</p> </dd></dl> <dl class="method"> <dt id="str.expandtabs"> <tt class="descclassname">str.</tt><tt class="descname">expandtabs</tt><big>(</big><span class="optional">[</span><em>tabsize</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#str.expandtabs" title="Permalink to this definition">¶</a></dt> <dd><p>Return a copy of the string where all tab characters are replaced by one or more spaces, depending on the current column and the given tab size. Tab positions occur every <em>tabsize</em> characters (default is 8, giving tab positions at columns 0, 8, 16 and so on). To expand the string, the current column is set to zero and the string is examined character by character. If the character is a tab (<tt class="docutils literal"><span class="pre">\t</span></tt>), one or more space characters are inserted in the result until the current column is equal to the next tab position. (The tab character itself is not copied.) If the character is a newline (<tt class="docutils literal"><span class="pre">\n</span></tt>) or return (<tt class="docutils literal"><span class="pre">\r</span></tt>), it is copied and the current column is reset to zero. Any other character is copied unchanged and the current column is incremented by one regardless of how the character is represented when printed.</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="s">'01</span><span class="se">\t</span><span class="s">012</span><span class="se">\t</span><span class="s">0123</span><span class="se">\t</span><span class="s">01234'</span><span class="o">.</span><span class="n">expandtabs</span><span class="p">()</span> <span class="go">'01 012 0123 01234'</span> <span class="gp">>>> </span><span class="s">'01</span><span class="se">\t</span><span class="s">012</span><span class="se">\t</span><span class="s">0123</span><span class="se">\t</span><span class="s">01234'</span><span class="o">.</span><span class="n">expandtabs</span><span class="p">(</span><span class="mi">4</span><span class="p">)</span> <span class="go">'01 012 0123 01234'</span> </pre></div> </div> </dd></dl> <dl class="method"> <dt id="str.find"> <tt class="descclassname">str.</tt><tt class="descname">find</tt><big>(</big><em>sub</em><span class="optional">[</span>, <em>start</em><span class="optional">[</span>, <em>end</em><span class="optional">]</span><span class="optional">]</span><big>)</big><a class="headerlink" href="#str.find" title="Permalink to this definition">¶</a></dt> <dd><p>Return the lowest index in the string where substring <em>sub</em> is found, such that <em>sub</em> is contained in the slice <tt class="docutils literal"><span class="pre">s[start:end]</span></tt>. Optional arguments <em>start</em> and <em>end</em> are interpreted as in slice notation. Return <tt class="docutils literal"><span class="pre">-1</span></tt> if <em>sub</em> is not found.</p> <div class="admonition note"> <p class="first admonition-title">Note</p> <p>The <a class="reference internal" href="#str.find" title="str.find"><tt class="xref py py-meth docutils literal"><span class="pre">find()</span></tt></a> method should be used only if you need to know the position of <em>sub</em>. To check if <em>sub</em> is a substring or not, use the <a class="reference internal" href="../reference/expressions.html#in"><tt class="xref std std-keyword docutils literal"><span class="pre">in</span></tt></a> operator:</p> <div class="last highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="s">'Py'</span> <span class="ow">in</span> <span class="s">'Python'</span> <span class="go">True</span> </pre></div> </div> </div> </dd></dl> <dl class="method"> <dt id="str.format"> <tt class="descclassname">str.</tt><tt class="descname">format</tt><big>(</big><em>*args</em>, <em>**kwargs</em><big>)</big><a class="headerlink" href="#str.format" title="Permalink to this definition">¶</a></dt> <dd><p>Perform a string formatting operation. The string on which this method is called can contain literal text or replacement fields delimited by braces <tt class="docutils literal"><span class="pre">{}</span></tt>. Each replacement field contains either the numeric index of a positional argument, or the name of a keyword argument. Returns a copy of the string where each replacement field is replaced with the string value of the corresponding argument.</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="s">"The sum of 1 + 2 is {0}"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="mi">1</span><span class="o">+</span><span class="mi">2</span><span class="p">)</span> <span class="go">'The sum of 1 + 2 is 3'</span> </pre></div> </div> <p>See <a class="reference internal" href="string.html#formatstrings"><em>Format String Syntax</em></a> for a description of the various formatting options that can be specified in format strings.</p> <p>This method of string formatting is the new standard in Python 3, and should be preferred to the <tt class="docutils literal"><span class="pre">%</span></tt> formatting described in <a class="reference internal" href="#string-formatting"><em>String Formatting Operations</em></a> in new code.</p> <p class="versionadded"> <span class="versionmodified">New in version 2.6.</span></p> </dd></dl> <dl class="method"> <dt id="str.index"> <tt class="descclassname">str.</tt><tt class="descname">index</tt><big>(</big><em>sub</em><span class="optional">[</span>, <em>start</em><span class="optional">[</span>, <em>end</em><span class="optional">]</span><span class="optional">]</span><big>)</big><a class="headerlink" href="#str.index" title="Permalink to this definition">¶</a></dt> <dd><p>Like <a class="reference internal" href="#str.find" title="str.find"><tt class="xref py py-meth docutils literal"><span class="pre">find()</span></tt></a>, but raise <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><tt class="xref py py-exc docutils literal"><span class="pre">ValueError</span></tt></a> when the substring is not found.</p> </dd></dl> <dl class="method"> <dt id="str.isalnum"> <tt class="descclassname">str.</tt><tt class="descname">isalnum</tt><big>(</big><big>)</big><a class="headerlink" href="#str.isalnum" title="Permalink to this definition">¶</a></dt> <dd><p>Return true if all characters in the string are alphanumeric and there is at least one character, false otherwise.</p> <p>For 8-bit strings, this method is locale-dependent.</p> </dd></dl> <dl class="method"> <dt id="str.isalpha"> <tt class="descclassname">str.</tt><tt class="descname">isalpha</tt><big>(</big><big>)</big><a class="headerlink" href="#str.isalpha" title="Permalink to this definition">¶</a></dt> <dd><p>Return true if all characters in the string are alphabetic and there is at least one character, false otherwise.</p> <p>For 8-bit strings, this method is locale-dependent.</p> </dd></dl> <dl class="method"> <dt id="str.isdigit"> <tt class="descclassname">str.</tt><tt class="descname">isdigit</tt><big>(</big><big>)</big><a class="headerlink" href="#str.isdigit" title="Permalink to this definition">¶</a></dt> <dd><p>Return true if all characters in the string are digits and there is at least one character, false otherwise.</p> <p>For 8-bit strings, this method is locale-dependent.</p> </dd></dl> <dl class="method"> <dt id="str.islower"> <tt class="descclassname">str.</tt><tt class="descname">islower</tt><big>(</big><big>)</big><a class="headerlink" href="#str.islower" title="Permalink to this definition">¶</a></dt> <dd><p>Return true if all cased characters <a class="footnote-reference" href="#id15" id="id6">[4]</a> in the string are lowercase and there is at least one cased character, false otherwise.</p> <p>For 8-bit strings, this method is locale-dependent.</p> </dd></dl> <dl class="method"> <dt id="str.isspace"> <tt class="descclassname">str.</tt><tt class="descname">isspace</tt><big>(</big><big>)</big><a class="headerlink" href="#str.isspace" title="Permalink to this definition">¶</a></dt> <dd><p>Return true if there are only whitespace characters in the string and there is at least one character, false otherwise.</p> <p>For 8-bit strings, this method is locale-dependent.</p> </dd></dl> <dl class="method"> <dt id="str.istitle"> <tt class="descclassname">str.</tt><tt class="descname">istitle</tt><big>(</big><big>)</big><a class="headerlink" href="#str.istitle" title="Permalink to this definition">¶</a></dt> <dd><p>Return true if the string is a titlecased string and there is at least one character, for example uppercase characters may only follow uncased characters and lowercase characters only cased ones. Return false otherwise.</p> <p>For 8-bit strings, this method is locale-dependent.</p> </dd></dl> <dl class="method"> <dt id="str.isupper"> <tt class="descclassname">str.</tt><tt class="descname">isupper</tt><big>(</big><big>)</big><a class="headerlink" href="#str.isupper" title="Permalink to this definition">¶</a></dt> <dd><p>Return true if all cased characters <a class="footnote-reference" href="#id15" id="id7">[4]</a> in the string are uppercase and there is at least one cased character, false otherwise.</p> <p>For 8-bit strings, this method is locale-dependent.</p> </dd></dl> <dl class="method"> <dt id="str.join"> <tt class="descclassname">str.</tt><tt class="descname">join</tt><big>(</big><em>iterable</em><big>)</big><a class="headerlink" href="#str.join" title="Permalink to this definition">¶</a></dt> <dd><p>Return a string which is the concatenation of the strings in the <a class="reference internal" href="../glossary.html#term-iterable"><em class="xref std std-term">iterable</em></a> <em>iterable</em>. The separator between elements is the string providing this method.</p> </dd></dl> <dl class="method"> <dt id="str.ljust"> <tt class="descclassname">str.</tt><tt class="descname">ljust</tt><big>(</big><em>width</em><span class="optional">[</span>, <em>fillchar</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#str.ljust" title="Permalink to this definition">¶</a></dt> <dd><p>Return the string left justified in a string of length <em>width</em>. Padding is done using the specified <em>fillchar</em> (default is a space). The original string is returned if <em>width</em> is less than or equal to <tt class="docutils literal"><span class="pre">len(s)</span></tt>.</p> <p class="versionchanged"> <span class="versionmodified">Changed in version 2.4: </span>Support for the <em>fillchar</em> argument.</p> </dd></dl> <dl class="method"> <dt id="str.lower"> <tt class="descclassname">str.</tt><tt class="descname">lower</tt><big>(</big><big>)</big><a class="headerlink" href="#str.lower" title="Permalink to this definition">¶</a></dt> <dd><p>Return a copy of the string with all the cased characters <a class="footnote-reference" href="#id15" id="id8">[4]</a> converted to lowercase.</p> <p>For 8-bit strings, this method is locale-dependent.</p> </dd></dl> <dl class="method"> <dt id="str.lstrip"> <tt class="descclassname">str.</tt><tt class="descname">lstrip</tt><big>(</big><span class="optional">[</span><em>chars</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#str.lstrip" title="Permalink to this definition">¶</a></dt> <dd><p>Return a copy of the string with leading characters removed. The <em>chars</em> argument is a string specifying the set of characters to be removed. If omitted or <tt class="docutils literal"><span class="pre">None</span></tt>, the <em>chars</em> argument defaults to removing whitespace. The <em>chars</em> argument is not a prefix; rather, all combinations of its values are stripped:</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="s">' spacious '</span><span class="o">.</span><span class="n">lstrip</span><span class="p">()</span> <span class="go">'spacious '</span> <span class="gp">>>> </span><span class="s">'www.example.com'</span><span class="o">.</span><span class="n">lstrip</span><span class="p">(</span><span class="s">'cmowz.'</span><span class="p">)</span> <span class="go">'example.com'</span> </pre></div> </div> <p class="versionchanged"> <span class="versionmodified">Changed in version 2.2.2: </span>Support for the <em>chars</em> argument.</p> </dd></dl> <dl class="method"> <dt id="str.partition"> <tt class="descclassname">str.</tt><tt class="descname">partition</tt><big>(</big><em>sep</em><big>)</big><a class="headerlink" href="#str.partition" title="Permalink to this definition">¶</a></dt> <dd><p>Split the string at the first occurrence of <em>sep</em>, and return a 3-tuple containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, return a 3-tuple containing the string itself, followed by two empty strings.</p> <p class="versionadded"> <span class="versionmodified">New in version 2.5.</span></p> </dd></dl> <dl class="method"> <dt id="str.replace"> <tt class="descclassname">str.</tt><tt class="descname">replace</tt><big>(</big><em>old</em>, <em>new</em><span class="optional">[</span>, <em>count</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#str.replace" title="Permalink to this definition">¶</a></dt> <dd><p>Return a copy of the string with all occurrences of substring <em>old</em> replaced by <em>new</em>. If the optional argument <em>count</em> is given, only the first <em>count</em> occurrences are replaced.</p> </dd></dl> <dl class="method"> <dt id="str.rfind"> <tt class="descclassname">str.</tt><tt class="descname">rfind</tt><big>(</big><em>sub</em><span class="optional">[</span>, <em>start</em><span class="optional">[</span>, <em>end</em><span class="optional">]</span><span class="optional">]</span><big>)</big><a class="headerlink" href="#str.rfind" title="Permalink to this definition">¶</a></dt> <dd><p>Return the highest index in the string where substring <em>sub</em> is found, such that <em>sub</em> is contained within <tt class="docutils literal"><span class="pre">s[start:end]</span></tt>. Optional arguments <em>start</em> and <em>end</em> are interpreted as in slice notation. Return <tt class="docutils literal"><span class="pre">-1</span></tt> on failure.</p> </dd></dl> <dl class="method"> <dt id="str.rindex"> <tt class="descclassname">str.</tt><tt class="descname">rindex</tt><big>(</big><em>sub</em><span class="optional">[</span>, <em>start</em><span class="optional">[</span>, <em>end</em><span class="optional">]</span><span class="optional">]</span><big>)</big><a class="headerlink" href="#str.rindex" title="Permalink to this definition">¶</a></dt> <dd><p>Like <a class="reference internal" href="#str.rfind" title="str.rfind"><tt class="xref py py-meth docutils literal"><span class="pre">rfind()</span></tt></a> but raises <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><tt class="xref py py-exc docutils literal"><span class="pre">ValueError</span></tt></a> when the substring <em>sub</em> is not found.</p> </dd></dl> <dl class="method"> <dt id="str.rjust"> <tt class="descclassname">str.</tt><tt class="descname">rjust</tt><big>(</big><em>width</em><span class="optional">[</span>, <em>fillchar</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#str.rjust" title="Permalink to this definition">¶</a></dt> <dd><p>Return the string right justified in a string of length <em>width</em>. Padding is done using the specified <em>fillchar</em> (default is a space). The original string is returned if <em>width</em> is less than or equal to <tt class="docutils literal"><span class="pre">len(s)</span></tt>.</p> <p class="versionchanged"> <span class="versionmodified">Changed in version 2.4: </span>Support for the <em>fillchar</em> argument.</p> </dd></dl> <dl class="method"> <dt id="str.rpartition"> <tt class="descclassname">str.</tt><tt class="descname">rpartition</tt><big>(</big><em>sep</em><big>)</big><a class="headerlink" href="#str.rpartition" title="Permalink to this definition">¶</a></dt> <dd><p>Split the string at the last occurrence of <em>sep</em>, and return a 3-tuple containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, return a 3-tuple containing two empty strings, followed by the string itself.</p> <p class="versionadded"> <span class="versionmodified">New in version 2.5.</span></p> </dd></dl> <dl class="method"> <dt id="str.rsplit"> <tt class="descclassname">str.</tt><tt class="descname">rsplit</tt><big>(</big><span class="optional">[</span><em>sep</em><span class="optional">[</span>, <em>maxsplit</em><span class="optional">]</span><span class="optional">]</span><big>)</big><a class="headerlink" href="#str.rsplit" title="Permalink to this definition">¶</a></dt> <dd><p>Return a list of the words in the string, using <em>sep</em> as the delimiter string. If <em>maxsplit</em> is given, at most <em>maxsplit</em> splits are done, the <em>rightmost</em> ones. If <em>sep</em> is not specified or <tt class="docutils literal"><span class="pre">None</span></tt>, any whitespace string is a separator. Except for splitting from the right, <a class="reference internal" href="#str.rsplit" title="str.rsplit"><tt class="xref py py-meth docutils literal"><span class="pre">rsplit()</span></tt></a> behaves like <a class="reference internal" href="#str.split" title="str.split"><tt class="xref py py-meth docutils literal"><span class="pre">split()</span></tt></a> which is described in detail below.</p> <p class="versionadded"> <span class="versionmodified">New in version 2.4.</span></p> </dd></dl> <dl class="method"> <dt id="str.rstrip"> <tt class="descclassname">str.</tt><tt class="descname">rstrip</tt><big>(</big><span class="optional">[</span><em>chars</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#str.rstrip" title="Permalink to this definition">¶</a></dt> <dd><p>Return a copy of the string with trailing characters removed. The <em>chars</em> argument is a string specifying the set of characters to be removed. If omitted or <tt class="docutils literal"><span class="pre">None</span></tt>, the <em>chars</em> argument defaults to removing whitespace. The <em>chars</em> argument is not a suffix; rather, all combinations of its values are stripped:</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="s">' spacious '</span><span class="o">.</span><span class="n">rstrip</span><span class="p">()</span> <span class="go">' spacious'</span> <span class="gp">>>> </span><span class="s">'mississippi'</span><span class="o">.</span><span class="n">rstrip</span><span class="p">(</span><span class="s">'ipz'</span><span class="p">)</span> <span class="go">'mississ'</span> </pre></div> </div> <p class="versionchanged"> <span class="versionmodified">Changed in version 2.2.2: </span>Support for the <em>chars</em> argument.</p> </dd></dl> <dl class="method"> <dt id="str.split"> <tt class="descclassname">str.</tt><tt class="descname">split</tt><big>(</big><span class="optional">[</span><em>sep</em><span class="optional">[</span>, <em>maxsplit</em><span class="optional">]</span><span class="optional">]</span><big>)</big><a class="headerlink" href="#str.split" title="Permalink to this definition">¶</a></dt> <dd><p>Return a list of the words in the string, using <em>sep</em> as the delimiter string. If <em>maxsplit</em> is given, at most <em>maxsplit</em> splits are done (thus, the list will have at most <tt class="docutils literal"><span class="pre">maxsplit+1</span></tt> elements). If <em>maxsplit</em> is not specified or <tt class="docutils literal"><span class="pre">-1</span></tt>, then there is no limit on the number of splits (all possible splits are made).</p> <p>If <em>sep</em> is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings (for example, <tt class="docutils literal"><span class="pre">'1,,2'.split(',')</span></tt> returns <tt class="docutils literal"><span class="pre">['1',</span> <span class="pre">'',</span> <span class="pre">'2']</span></tt>). The <em>sep</em> argument may consist of multiple characters (for example, <tt class="docutils literal"><span class="pre">'1<>2<>3'.split('<>')</span></tt> returns <tt class="docutils literal"><span class="pre">['1',</span> <span class="pre">'2',</span> <span class="pre">'3']</span></tt>). Splitting an empty string with a specified separator returns <tt class="docutils literal"><span class="pre">['']</span></tt>.</p> <p>If <em>sep</em> is not specified or is <tt class="docutils literal"><span class="pre">None</span></tt>, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace. Consequently, splitting an empty string or a string consisting of just whitespace with a <tt class="docutils literal"><span class="pre">None</span></tt> separator returns <tt class="docutils literal"><span class="pre">[]</span></tt>.</p> <p>For example, <tt class="docutils literal"><span class="pre">'</span> <span class="pre">1</span> <span class="pre">2</span> <span class="pre">3</span> <span class="pre">'.split()</span></tt> returns <tt class="docutils literal"><span class="pre">['1',</span> <span class="pre">'2',</span> <span class="pre">'3']</span></tt>, and <tt class="docutils literal"><span class="pre">'</span> <span class="pre">1</span> <span class="pre">2</span> <span class="pre">3</span> <span class="pre">'.split(None,</span> <span class="pre">1)</span></tt> returns <tt class="docutils literal"><span class="pre">['1',</span> <span class="pre">'2</span> <span class="pre">3</span> <span class="pre">']</span></tt>.</p> </dd></dl> <span class="target" id="index-24"></span><dl class="method"> <dt id="str.splitlines"> <tt class="descclassname">str.</tt><tt class="descname">splitlines</tt><big>(</big><span class="optional">[</span><em>keepends</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#str.splitlines" title="Permalink to this definition">¶</a></dt> <dd><p>Return a list of the lines in the string, breaking at line boundaries. This method uses the <a class="reference internal" href="../glossary.html#term-universal-newlines"><em class="xref std std-term">universal newlines</em></a> approach to splitting lines. Line breaks are not included in the resulting list unless <em>keepends</em> is given and true.</p> <p>For example, <tt class="docutils literal"><span class="pre">'ab</span> <span class="pre">c\n\nde</span> <span class="pre">fg\rkl\r\n'.splitlines()</span></tt> returns <tt class="docutils literal"><span class="pre">['ab</span> <span class="pre">c',</span> <span class="pre">'',</span> <span class="pre">'de</span> <span class="pre">fg',</span> <span class="pre">'kl']</span></tt>, while the same call with <tt class="docutils literal"><span class="pre">splitlines(True)</span></tt> returns <tt class="docutils literal"><span class="pre">['ab</span> <span class="pre">c\n',</span> <span class="pre">'\n',</span> <span class="pre">'de</span> <span class="pre">fg\r',</span> <span class="pre">'kl\r\n']</span></tt>.</p> <p>Unlike <a class="reference internal" href="#str.split" title="str.split"><tt class="xref py py-meth docutils literal"><span class="pre">split()</span></tt></a> when a delimiter string <em>sep</em> is given, this method returns an empty list for the empty string, and a terminal line break does not result in an extra line.</p> </dd></dl> <dl class="method"> <dt id="str.startswith"> <tt class="descclassname">str.</tt><tt class="descname">startswith</tt><big>(</big><em>prefix</em><span class="optional">[</span>, <em>start</em><span class="optional">[</span>, <em>end</em><span class="optional">]</span><span class="optional">]</span><big>)</big><a class="headerlink" href="#str.startswith" title="Permalink to this definition">¶</a></dt> <dd><p>Return <tt class="docutils literal"><span class="pre">True</span></tt> if string starts with the <em>prefix</em>, otherwise return <tt class="docutils literal"><span class="pre">False</span></tt>. <em>prefix</em> can also be a tuple of prefixes to look for. With optional <em>start</em>, test string beginning at that position. With optional <em>end</em>, stop comparing string at that position.</p> <p class="versionchanged"> <span class="versionmodified">Changed in version 2.5: </span>Accept tuples as <em>prefix</em>.</p> </dd></dl> <dl class="method"> <dt id="str.strip"> <tt class="descclassname">str.</tt><tt class="descname">strip</tt><big>(</big><span class="optional">[</span><em>chars</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#str.strip" title="Permalink to this definition">¶</a></dt> <dd><p>Return a copy of the string with the leading and trailing characters removed. The <em>chars</em> argument is a string specifying the set of characters to be removed. If omitted or <tt class="docutils literal"><span class="pre">None</span></tt>, the <em>chars</em> argument defaults to removing whitespace. The <em>chars</em> argument is not a prefix or suffix; rather, all combinations of its values are stripped:</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="s">' spacious '</span><span class="o">.</span><span class="n">strip</span><span class="p">()</span> <span class="go">'spacious'</span> <span class="gp">>>> </span><span class="s">'www.example.com'</span><span class="o">.</span><span class="n">strip</span><span class="p">(</span><span class="s">'cmowz.'</span><span class="p">)</span> <span class="go">'example'</span> </pre></div> </div> <p class="versionchanged"> <span class="versionmodified">Changed in version 2.2.2: </span>Support for the <em>chars</em> argument.</p> </dd></dl> <dl class="method"> <dt id="str.swapcase"> <tt class="descclassname">str.</tt><tt class="descname">swapcase</tt><big>(</big><big>)</big><a class="headerlink" href="#str.swapcase" title="Permalink to this definition">¶</a></dt> <dd><p>Return a copy of the string with uppercase characters converted to lowercase and vice versa.</p> <p>For 8-bit strings, this method is locale-dependent.</p> </dd></dl> <dl class="method"> <dt id="str.title"> <tt class="descclassname">str.</tt><tt class="descname">title</tt><big>(</big><big>)</big><a class="headerlink" href="#str.title" title="Permalink to this definition">¶</a></dt> <dd><p>Return a titlecased version of the string where words start with an uppercase character and the remaining characters are lowercase.</p> <p>The algorithm uses a simple language-independent definition of a word as groups of consecutive letters. The definition works in many contexts but it means that apostrophes in contractions and possessives form word boundaries, which may not be the desired result:</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="s">"they're bill's friends from the UK"</span><span class="o">.</span><span class="n">title</span><span class="p">()</span> <span class="go">"They'Re Bill'S Friends From The Uk"</span> </pre></div> </div> <p>A workaround for apostrophes can be constructed using regular expressions:</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="kn">import</span> <span class="nn">re</span> <span class="gp">>>> </span><span class="k">def</span> <span class="nf">titlecase</span><span class="p">(</span><span class="n">s</span><span class="p">):</span> <span class="gp">... </span> <span class="k">return</span> <span class="n">re</span><span class="o">.</span><span class="n">sub</span><span class="p">(</span><span class="s">r"[A-Za-z]+('[A-Za-z]+)?"</span><span class="p">,</span> <span class="gp">... </span> <span class="k">lambda</span> <span class="n">mo</span><span class="p">:</span> <span class="n">mo</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">0</span><span class="p">)[</span><span class="mi">0</span><span class="p">]</span><span class="o">.</span><span class="n">upper</span><span class="p">()</span> <span class="o">+</span> <span class="gp">... </span> <span class="n">mo</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">0</span><span class="p">)[</span><span class="mi">1</span><span class="p">:]</span><span class="o">.</span><span class="n">lower</span><span class="p">(),</span> <span class="gp">... </span> <span class="n">s</span><span class="p">)</span> <span class="gp">...</span> <span class="gp">>>> </span><span class="n">titlecase</span><span class="p">(</span><span class="s">"they're bill's friends."</span><span class="p">)</span> <span class="go">"They're Bill's Friends."</span> </pre></div> </div> <p>For 8-bit strings, this method is locale-dependent.</p> </dd></dl> <dl class="method"> <dt id="str.translate"> <tt class="descclassname">str.</tt><tt class="descname">translate</tt><big>(</big><em>table</em><span class="optional">[</span>, <em>deletechars</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#str.translate" title="Permalink to this definition">¶</a></dt> <dd><p>Return a copy of the string where all characters occurring in the optional argument <em>deletechars</em> are removed, and the remaining characters have been mapped through the given translation table, which must be a string of length 256.</p> <p>You can use the <a class="reference internal" href="string.html#string.maketrans" title="string.maketrans"><tt class="xref py py-func docutils literal"><span class="pre">maketrans()</span></tt></a> helper function in the <a class="reference internal" href="string.html#module-string" title="string: Common string operations."><tt class="xref py py-mod docutils literal"><span class="pre">string</span></tt></a> module to create a translation table. For string objects, set the <em>table</em> argument to <tt class="docutils literal"><span class="pre">None</span></tt> for translations that only delete characters:</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="s">'read this short text'</span><span class="o">.</span><span class="n">translate</span><span class="p">(</span><span class="bp">None</span><span class="p">,</span> <span class="s">'aeiou'</span><span class="p">)</span> <span class="go">'rd ths shrt txt'</span> </pre></div> </div> <p class="versionadded"> <span class="versionmodified">New in version 2.6: </span>Support for a <tt class="docutils literal"><span class="pre">None</span></tt> <em>table</em> argument.</p> <p>For Unicode objects, the <a class="reference internal" href="#str.translate" title="str.translate"><tt class="xref py py-meth docutils literal"><span class="pre">translate()</span></tt></a> method does not accept the optional <em>deletechars</em> argument. Instead, it returns a copy of the <em>s</em> where all characters have been mapped through the given translation table which must be a mapping of Unicode ordinals to Unicode ordinals, Unicode strings or <tt class="docutils literal"><span class="pre">None</span></tt>. Unmapped characters are left untouched. Characters mapped to <tt class="docutils literal"><span class="pre">None</span></tt> are deleted. Note, a more flexible approach is to create a custom character mapping codec using the <a class="reference internal" href="codecs.html#module-codecs" title="codecs: Encode and decode data and streams."><tt class="xref py py-mod docutils literal"><span class="pre">codecs</span></tt></a> module (see <tt class="xref py py-mod docutils literal"><span class="pre">encodings.cp1251</span></tt> for an example).</p> </dd></dl> <dl class="method"> <dt id="str.upper"> <tt class="descclassname">str.</tt><tt class="descname">upper</tt><big>(</big><big>)</big><a class="headerlink" href="#str.upper" title="Permalink to this definition">¶</a></dt> <dd><p>Return a copy of the string with all the cased characters <a class="footnote-reference" href="#id15" id="id9">[4]</a> converted to uppercase. Note that <tt class="docutils literal"><span class="pre">str.upper().isupper()</span></tt> might be <tt class="docutils literal"><span class="pre">False</span></tt> if <tt class="docutils literal"><span class="pre">s</span></tt> contains uncased characters or if the Unicode category of the resulting character(s) is not “Lu” (Letter, uppercase), but e.g. “Lt” (Letter, titlecase).</p> <p>For 8-bit strings, this method is locale-dependent.</p> </dd></dl> <dl class="method"> <dt id="str.zfill"> <tt class="descclassname">str.</tt><tt class="descname">zfill</tt><big>(</big><em>width</em><big>)</big><a class="headerlink" href="#str.zfill" title="Permalink to this definition">¶</a></dt> <dd><p>Return the numeric string left filled with zeros in a string of length <em>width</em>. A sign prefix is handled correctly. The original string is returned if <em>width</em> is less than or equal to <tt class="docutils literal"><span class="pre">len(s)</span></tt>.</p> <p class="versionadded"> <span class="versionmodified">New in version 2.2.2.</span></p> </dd></dl> <p>The following methods are present only on unicode objects:</p> <dl class="method"> <dt id="unicode.isnumeric"> <tt class="descclassname">unicode.</tt><tt class="descname">isnumeric</tt><big>(</big><big>)</big><a class="headerlink" href="#unicode.isnumeric" title="Permalink to this definition">¶</a></dt> <dd><p>Return <tt class="docutils literal"><span class="pre">True</span></tt> if there are only numeric characters in S, <tt class="docutils literal"><span class="pre">False</span></tt> otherwise. Numeric characters include digit characters, and all characters that have the Unicode numeric value property, e.g. U+2155, VULGAR FRACTION ONE FIFTH.</p> </dd></dl> <dl class="method"> <dt id="unicode.isdecimal"> <tt class="descclassname">unicode.</tt><tt class="descname">isdecimal</tt><big>(</big><big>)</big><a class="headerlink" href="#unicode.isdecimal" title="Permalink to this definition">¶</a></dt> <dd><p>Return <tt class="docutils literal"><span class="pre">True</span></tt> if there are only decimal characters in S, <tt class="docutils literal"><span class="pre">False</span></tt> otherwise. Decimal characters include digit characters, and all characters that can be used to form decimal-radix numbers, e.g. U+0660, ARABIC-INDIC DIGIT ZERO.</p> </dd></dl> </div> <div class="section" id="string-formatting-operations"> <span id="string-formatting"></span><h3>5.6.2. String Formatting Operations<a class="headerlink" href="#string-formatting-operations" title="Permalink to this headline">¶</a></h3> <p id="index-25">String and Unicode objects have one unique built-in operation: the <tt class="docutils literal"><span class="pre">%</span></tt> operator (modulo). This is also known as the string <em>formatting</em> or <em>interpolation</em> operator. Given <tt class="docutils literal"><span class="pre">format</span> <span class="pre">%</span> <span class="pre">values</span></tt> (where <em>format</em> is a string or Unicode object), <tt class="docutils literal"><span class="pre">%</span></tt> conversion specifications in <em>format</em> are replaced with zero or more elements of <em>values</em>. The effect is similar to the using <tt class="xref c c-func docutils literal"><span class="pre">sprintf()</span></tt> in the C language. If <em>format</em> is a Unicode object, or if any of the objects being converted using the <tt class="docutils literal"><span class="pre">%s</span></tt> conversion are Unicode objects, the result will also be a Unicode object.</p> <p>If <em>format</em> requires a single argument, <em>values</em> may be a single non-tuple object. <a class="footnote-reference" href="#id16" id="id10">[5]</a> Otherwise, <em>values</em> must be a tuple with exactly the number of items specified by the format string, or a single mapping object (for example, a dictionary).</p> <p>A conversion specifier contains two or more characters and has the following components, which must occur in this order:</p> <ol class="arabic simple"> <li>The <tt class="docutils literal"><span class="pre">'%'</span></tt> character, which marks the start of the specifier.</li> <li>Mapping key (optional), consisting of a parenthesised sequence of characters (for example, <tt class="docutils literal"><span class="pre">(somename)</span></tt>).</li> <li>Conversion flags (optional), which affect the result of some conversion types.</li> <li>Minimum field width (optional). If specified as an <tt class="docutils literal"><span class="pre">'*'</span></tt> (asterisk), the actual width is read from the next element of the tuple in <em>values</em>, and the object to convert comes after the minimum field width and optional precision.</li> <li>Precision (optional), given as a <tt class="docutils literal"><span class="pre">'.'</span></tt> (dot) followed by the precision. If specified as <tt class="docutils literal"><span class="pre">'*'</span></tt> (an asterisk), the actual width is read from the next element of the tuple in <em>values</em>, and the value to convert comes after the precision.</li> <li>Length modifier (optional).</li> <li>Conversion type.</li> </ol> <p>When the right argument is a dictionary (or other mapping type), then the formats in the string <em>must</em> include a parenthesised mapping key into that dictionary inserted immediately after the <tt class="docutils literal"><span class="pre">'%'</span></tt> character. The mapping key selects the value to be formatted from the mapping. For example:</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="k">print</span> <span class="s">'</span><span class="si">%(language)s</span><span class="s"> has </span><span class="si">%(number)03d</span><span class="s"> quote types.'</span> <span class="o">%</span> \ <span class="gp">... </span> <span class="p">{</span><span class="s">"language"</span><span class="p">:</span> <span class="s">"Python"</span><span class="p">,</span> <span class="s">"number"</span><span class="p">:</span> <span class="mi">2</span><span class="p">}</span> <span class="go">Python has 002 quote types.</span> </pre></div> </div> <p>In this case no <tt class="docutils literal"><span class="pre">*</span></tt> specifiers may occur in a format (since they require a sequential parameter list).</p> <p>The conversion flag characters are:</p> <table border="1" class="docutils"> <colgroup> <col width="12%" /> <col width="88%" /> </colgroup> <thead valign="bottom"> <tr class="row-odd"><th class="head">Flag</th> <th class="head">Meaning</th> </tr> </thead> <tbody valign="top"> <tr class="row-even"><td><tt class="docutils literal"><span class="pre">'#'</span></tt></td> <td>The value conversion will use the “alternate form” (where defined below).</td> </tr> <tr class="row-odd"><td><tt class="docutils literal"><span class="pre">'0'</span></tt></td> <td>The conversion will be zero padded for numeric values.</td> </tr> <tr class="row-even"><td><tt class="docutils literal"><span class="pre">'-'</span></tt></td> <td>The converted value is left adjusted (overrides the <tt class="docutils literal"><span class="pre">'0'</span></tt> conversion if both are given).</td> </tr> <tr class="row-odd"><td><tt class="docutils literal"><span class="pre">'</span> <span class="pre">'</span></tt></td> <td>(a space) A blank should be left before a positive number (or empty string) produced by a signed conversion.</td> </tr> <tr class="row-even"><td><tt class="docutils literal"><span class="pre">'+'</span></tt></td> <td>A sign character (<tt class="docutils literal"><span class="pre">'+'</span></tt> or <tt class="docutils literal"><span class="pre">'-'</span></tt>) will precede the conversion (overrides a “space” flag).</td> </tr> </tbody> </table> <p>A length modifier (<tt class="docutils literal"><span class="pre">h</span></tt>, <tt class="docutils literal"><span class="pre">l</span></tt>, or <tt class="docutils literal"><span class="pre">L</span></tt>) may be present, but is ignored as it is not necessary for Python – so e.g. <tt class="docutils literal"><span class="pre">%ld</span></tt> is identical to <tt class="docutils literal"><span class="pre">%d</span></tt>.</p> <p>The conversion types are:</p> <table border="1" class="docutils"> <colgroup> <col width="17%" /> <col width="74%" /> <col width="10%" /> </colgroup> <thead valign="bottom"> <tr class="row-odd"><th class="head">Conversion</th> <th class="head">Meaning</th> <th class="head">Notes</th> </tr> </thead> <tbody valign="top"> <tr class="row-even"><td><tt class="docutils literal"><span class="pre">'d'</span></tt></td> <td>Signed integer decimal.</td> <td> </td> </tr> <tr class="row-odd"><td><tt class="docutils literal"><span class="pre">'i'</span></tt></td> <td>Signed integer decimal.</td> <td> </td> </tr> <tr class="row-even"><td><tt class="docutils literal"><span class="pre">'o'</span></tt></td> <td>Signed octal value.</td> <td>(1)</td> </tr> <tr class="row-odd"><td><tt class="docutils literal"><span class="pre">'u'</span></tt></td> <td>Obsolete type – it is identical to <tt class="docutils literal"><span class="pre">'d'</span></tt>.</td> <td>(7)</td> </tr> <tr class="row-even"><td><tt class="docutils literal"><span class="pre">'x'</span></tt></td> <td>Signed hexadecimal (lowercase).</td> <td>(2)</td> </tr> <tr class="row-odd"><td><tt class="docutils literal"><span class="pre">'X'</span></tt></td> <td>Signed hexadecimal (uppercase).</td> <td>(2)</td> </tr> <tr class="row-even"><td><tt class="docutils literal"><span class="pre">'e'</span></tt></td> <td>Floating point exponential format (lowercase).</td> <td>(3)</td> </tr> <tr class="row-odd"><td><tt class="docutils literal"><span class="pre">'E'</span></tt></td> <td>Floating point exponential format (uppercase).</td> <td>(3)</td> </tr> <tr class="row-even"><td><tt class="docutils literal"><span class="pre">'f'</span></tt></td> <td>Floating point decimal format.</td> <td>(3)</td> </tr> <tr class="row-odd"><td><tt class="docutils literal"><span class="pre">'F'</span></tt></td> <td>Floating point decimal format.</td> <td>(3)</td> </tr> <tr class="row-even"><td><tt class="docutils literal"><span class="pre">'g'</span></tt></td> <td>Floating point format. Uses lowercase exponential format if exponent is less than -4 or not less than precision, decimal format otherwise.</td> <td>(4)</td> </tr> <tr class="row-odd"><td><tt class="docutils literal"><span class="pre">'G'</span></tt></td> <td>Floating point format. Uses uppercase exponential format if exponent is less than -4 or not less than precision, decimal format otherwise.</td> <td>(4)</td> </tr> <tr class="row-even"><td><tt class="docutils literal"><span class="pre">'c'</span></tt></td> <td>Single character (accepts integer or single character string).</td> <td> </td> </tr> <tr class="row-odd"><td><tt class="docutils literal"><span class="pre">'r'</span></tt></td> <td>String (converts any Python object using <a class="reference internal" href="functions.html#func-repr"><em>repr()</em></a>).</td> <td>(5)</td> </tr> <tr class="row-even"><td><tt class="docutils literal"><span class="pre">'s'</span></tt></td> <td>String (converts any Python object using <a class="reference internal" href="functions.html#str" title="str"><tt class="xref py py-func docutils literal"><span class="pre">str()</span></tt></a>).</td> <td>(6)</td> </tr> <tr class="row-odd"><td><tt class="docutils literal"><span class="pre">'%'</span></tt></td> <td>No argument is converted, results in a <tt class="docutils literal"><span class="pre">'%'</span></tt> character in the result.</td> <td> </td> </tr> </tbody> </table> <p>Notes:</p> <ol class="arabic"> <li><p class="first">The alternate form causes a leading zero (<tt class="docutils literal"><span class="pre">'0'</span></tt>) to be inserted between left-hand padding and the formatting of the number if the leading character of the result is not already a zero.</p> </li> <li><p class="first">The alternate form causes a leading <tt class="docutils literal"><span class="pre">'0x'</span></tt> or <tt class="docutils literal"><span class="pre">'0X'</span></tt> (depending on whether the <tt class="docutils literal"><span class="pre">'x'</span></tt> or <tt class="docutils literal"><span class="pre">'X'</span></tt> format was used) to be inserted between left-hand padding and the formatting of the number if the leading character of the result is not already a zero.</p> </li> <li><p class="first">The alternate form causes the result to always contain a decimal point, even if no digits follow it.</p> <p>The precision determines the number of digits after the decimal point and defaults to 6.</p> </li> <li><p class="first">The alternate form causes the result to always contain a decimal point, and trailing zeroes are not removed as they would otherwise be.</p> <p>The precision determines the number of significant digits before and after the decimal point and defaults to 6.</p> </li> <li><p class="first">The <tt class="docutils literal"><span class="pre">%r</span></tt> conversion was added in Python 2.0.</p> <p>The precision determines the maximal number of characters used.</p> </li> <li><p class="first">If the object or format provided is a <a class="reference internal" href="functions.html#unicode" title="unicode"><tt class="xref py py-class docutils literal"><span class="pre">unicode</span></tt></a> string, the resulting string will also be <a class="reference internal" href="functions.html#unicode" title="unicode"><tt class="xref py py-class docutils literal"><span class="pre">unicode</span></tt></a>.</p> <p>The precision determines the maximal number of characters used.</p> </li> <li><p class="first">See <span class="target" id="index-26"></span><a class="pep reference external" href="http://www.python.org/dev/peps/pep-0237"><strong>PEP 237</strong></a>.</p> </li> </ol> <p>Since Python strings have an explicit length, <tt class="docutils literal"><span class="pre">%s</span></tt> conversions do not assume that <tt class="docutils literal"><span class="pre">'\0'</span></tt> is the end of the string.</p> <p class="versionchanged"> <span class="versionmodified">Changed in version 2.7: </span><tt class="docutils literal"><span class="pre">%f</span></tt> conversions for numbers whose absolute value is over 1e50 are no longer replaced by <tt class="docutils literal"><span class="pre">%g</span></tt> conversions.</p> <p id="index-27">Additional string operations are defined in standard modules <a class="reference internal" href="string.html#module-string" title="string: Common string operations."><tt class="xref py py-mod docutils literal"><span class="pre">string</span></tt></a> and <a class="reference internal" href="re.html#module-re" title="re: Regular expression operations."><tt class="xref py py-mod docutils literal"><span class="pre">re</span></tt></a>.</p> </div> <div class="section" id="xrange-type"> <span id="typesseq-xrange"></span><h3>5.6.3. XRange Type<a class="headerlink" href="#xrange-type" title="Permalink to this headline">¶</a></h3> <p id="index-28">The <a class="reference internal" href="functions.html#xrange" title="xrange"><tt class="xref py py-class docutils literal"><span class="pre">xrange</span></tt></a> type is an immutable sequence which is commonly used for looping. The advantage of the <a class="reference internal" href="functions.html#xrange" title="xrange"><tt class="xref py py-class docutils literal"><span class="pre">xrange</span></tt></a> type is that an <a class="reference internal" href="functions.html#xrange" title="xrange"><tt class="xref py py-class docutils literal"><span class="pre">xrange</span></tt></a> object will always take the same amount of memory, no matter the size of the range it represents. There are no consistent performance advantages.</p> <p>XRange objects have very little behavior: they only support indexing, iteration, and the <a class="reference internal" href="functions.html#len" title="len"><tt class="xref py py-func docutils literal"><span class="pre">len()</span></tt></a> function.</p> </div> <div class="section" id="mutable-sequence-types"> <span id="typesseq-mutable"></span><h3>5.6.4. Mutable Sequence Types<a class="headerlink" href="#mutable-sequence-types" title="Permalink to this headline">¶</a></h3> <p id="index-29">List and <a class="reference internal" href="functions.html#bytearray" title="bytearray"><tt class="xref py py-class docutils literal"><span class="pre">bytearray</span></tt></a> objects support additional operations that allow in-place modification of the object. Other mutable sequence types (when added to the language) should also support these operations. Strings and tuples are immutable sequence types: such objects cannot be modified once created. The following operations are defined on mutable sequence types (where <em>x</em> is an arbitrary object):</p> <table border="1" class="docutils" id="index-30"> <colgroup> <col width="36%" /> <col width="39%" /> <col width="25%" /> </colgroup> <thead valign="bottom"> <tr class="row-odd"><th class="head">Operation</th> <th class="head">Result</th> <th class="head">Notes</th> </tr> </thead> <tbody valign="top"> <tr class="row-even"><td><tt class="docutils literal"><span class="pre">s[i]</span> <span class="pre">=</span> <span class="pre">x</span></tt></td> <td>item <em>i</em> of <em>s</em> is replaced by <em>x</em></td> <td> </td> </tr> <tr class="row-odd"><td><tt class="docutils literal"><span class="pre">s[i:j]</span> <span class="pre">=</span> <span class="pre">t</span></tt></td> <td>slice of <em>s</em> from <em>i</em> to <em>j</em> is replaced by the contents of the iterable <em>t</em></td> <td> </td> </tr> <tr class="row-even"><td><tt class="docutils literal"><span class="pre">del</span> <span class="pre">s[i:j]</span></tt></td> <td>same as <tt class="docutils literal"><span class="pre">s[i:j]</span> <span class="pre">=</span> <span class="pre">[]</span></tt></td> <td> </td> </tr> <tr class="row-odd"><td><tt class="docutils literal"><span class="pre">s[i:j:k]</span> <span class="pre">=</span> <span class="pre">t</span></tt></td> <td>the elements of <tt class="docutils literal"><span class="pre">s[i:j:k]</span></tt> are replaced by those of <em>t</em></td> <td>(1)</td> </tr> <tr class="row-even"><td><tt class="docutils literal"><span class="pre">del</span> <span class="pre">s[i:j:k]</span></tt></td> <td>removes the elements of <tt class="docutils literal"><span class="pre">s[i:j:k]</span></tt> from the list</td> <td> </td> </tr> <tr class="row-odd"><td><tt class="docutils literal"><span class="pre">s.append(x)</span></tt></td> <td>same as <tt class="docutils literal"><span class="pre">s[len(s):len(s)]</span> <span class="pre">=</span> <span class="pre">[x]</span></tt></td> <td>(2)</td> </tr> <tr class="row-even"><td><tt class="docutils literal"><span class="pre">s.extend(x)</span></tt></td> <td>same as <tt class="docutils literal"><span class="pre">s[len(s):len(s)]</span> <span class="pre">=</span> <span class="pre">x</span></tt></td> <td>(3)</td> </tr> <tr class="row-odd"><td><tt class="docutils literal"><span class="pre">s.count(x)</span></tt></td> <td>return number of <em>i</em>‘s for which <tt class="docutils literal"><span class="pre">s[i]</span> <span class="pre">==</span> <span class="pre">x</span></tt></td> <td> </td> </tr> <tr class="row-even"><td><tt class="docutils literal"><span class="pre">s.index(x[,</span> <span class="pre">i[,</span> <span class="pre">j]])</span></tt></td> <td>return smallest <em>k</em> such that <tt class="docutils literal"><span class="pre">s[k]</span> <span class="pre">==</span> <span class="pre">x</span></tt> and <tt class="docutils literal"><span class="pre">i</span> <span class="pre"><=</span> <span class="pre">k</span> <span class="pre"><</span> <span class="pre">j</span></tt></td> <td>(4)</td> </tr> <tr class="row-odd"><td><tt class="docutils literal"><span class="pre">s.insert(i,</span> <span class="pre">x)</span></tt></td> <td>same as <tt class="docutils literal"><span class="pre">s[i:i]</span> <span class="pre">=</span> <span class="pre">[x]</span></tt></td> <td>(5)</td> </tr> <tr class="row-even"><td><tt class="docutils literal"><span class="pre">s.pop([i])</span></tt></td> <td>same as <tt class="docutils literal"><span class="pre">x</span> <span class="pre">=</span> <span class="pre">s[i];</span> <span class="pre">del</span> <span class="pre">s[i];</span> <span class="pre">return</span> <span class="pre">x</span></tt></td> <td>(6)</td> </tr> <tr class="row-odd"><td><tt class="docutils literal"><span class="pre">s.remove(x)</span></tt></td> <td>same as <tt class="docutils literal"><span class="pre">del</span> <span class="pre">s[s.index(x)]</span></tt></td> <td>(4)</td> </tr> <tr class="row-even"><td><tt class="docutils literal"><span class="pre">s.reverse()</span></tt></td> <td>reverses the items of <em>s</em> in place</td> <td>(7)</td> </tr> <tr class="row-odd"><td><tt class="docutils literal"><span class="pre">s.sort([cmp[,</span> <span class="pre">key[,</span> <span class="pre">reverse]]])</span></tt></td> <td>sort the items of <em>s</em> in place</td> <td>(7)(8)(9)(10)</td> </tr> </tbody> </table> <p>Notes:</p> <ol class="arabic"> <li><p class="first"><em>t</em> must have the same length as the slice it is replacing.</p> </li> <li><p class="first">The C implementation of Python has historically accepted multiple parameters and implicitly joined them into a tuple; this no longer works in Python 2.0. Use of this misfeature has been deprecated since Python 1.4.</p> </li> <li><p class="first"><em>x</em> can be any iterable object.</p> </li> <li><p class="first">Raises <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><tt class="xref py py-exc docutils literal"><span class="pre">ValueError</span></tt></a> when <em>x</em> is not found in <em>s</em>. When a negative index is passed as the second or third parameter to the <tt class="xref py py-meth docutils literal"><span class="pre">index()</span></tt> method, the list length is added, as for slice indices. If it is still negative, it is truncated to zero, as for slice indices.</p> <p class="versionchanged"> <span class="versionmodified">Changed in version 2.3: </span>Previously, <tt class="xref py py-meth docutils literal"><span class="pre">index()</span></tt> didn’t have arguments for specifying start and stop positions.</p> </li> <li><p class="first">When a negative index is passed as the first parameter to the <tt class="xref py py-meth docutils literal"><span class="pre">insert()</span></tt> method, the list length is added, as for slice indices. If it is still negative, it is truncated to zero, as for slice indices.</p> <p class="versionchanged"> <span class="versionmodified">Changed in version 2.3: </span>Previously, all negative indices were truncated to zero.</p> </li> <li><p class="first">The <tt class="xref py py-meth docutils literal"><span class="pre">pop()</span></tt> method is only supported by the list and array types. The optional argument <em>i</em> defaults to <tt class="docutils literal"><span class="pre">-1</span></tt>, so that by default the last item is removed and returned.</p> </li> <li><p class="first">The <tt class="xref py py-meth docutils literal"><span class="pre">sort()</span></tt> and <tt class="xref py py-meth docutils literal"><span class="pre">reverse()</span></tt> methods modify the list in place for economy of space when sorting or reversing a large list. To remind you that they operate by side effect, they don’t return the sorted or reversed list.</p> </li> <li><p class="first">The <tt class="xref py py-meth docutils literal"><span class="pre">sort()</span></tt> method takes optional arguments for controlling the comparisons.</p> <p><em>cmp</em> specifies a custom comparison function of two arguments (list items) which should return a negative, zero or positive number depending on whether the first argument is considered smaller than, equal to, or larger than the second argument: <tt class="docutils literal"><span class="pre">cmp=lambda</span> <span class="pre">x,y:</span> <span class="pre">cmp(x.lower(),</span> <span class="pre">y.lower())</span></tt>. The default value is <tt class="docutils literal"><span class="pre">None</span></tt>.</p> <p><em>key</em> specifies a function of one argument that is used to extract a comparison key from each list element: <tt class="docutils literal"><span class="pre">key=str.lower</span></tt>. The default value is <tt class="docutils literal"><span class="pre">None</span></tt>.</p> <p><em>reverse</em> is a boolean value. If set to <tt class="docutils literal"><span class="pre">True</span></tt>, then the list elements are sorted as if each comparison were reversed.</p> <p>In general, the <em>key</em> and <em>reverse</em> conversion processes are much faster than specifying an equivalent <em>cmp</em> function. This is because <em>cmp</em> is called multiple times for each list element while <em>key</em> and <em>reverse</em> touch each element only once. Use <a class="reference internal" href="functools.html#functools.cmp_to_key" title="functools.cmp_to_key"><tt class="xref py py-func docutils literal"><span class="pre">functools.cmp_to_key()</span></tt></a> to convert an old-style <em>cmp</em> function to a <em>key</em> function.</p> <p class="versionchanged"> <span class="versionmodified">Changed in version 2.3: </span>Support for <tt class="docutils literal"><span class="pre">None</span></tt> as an equivalent to omitting <em>cmp</em> was added.</p> <p class="versionchanged"> <span class="versionmodified">Changed in version 2.4: </span>Support for <em>key</em> and <em>reverse</em> was added.</p> </li> <li><p class="first">Starting with Python 2.3, the <tt class="xref py py-meth docutils literal"><span class="pre">sort()</span></tt> method is guaranteed to be stable. A sort is stable if it guarantees not to change the relative order of elements that compare equal — this is helpful for sorting in multiple passes (for example, sort by department, then by salary grade).</p> </li> <li><div class="impl-detail first compound"> <p><strong>CPython implementation detail:</strong> While a list is being sorted, the effect of attempting to mutate, or even inspect, the list is undefined. The C implementation of Python 2.3 and newer makes the list appear empty for the duration, and raises <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><tt class="xref py py-exc docutils literal"><span class="pre">ValueError</span></tt></a> if it can detect that the list has been mutated during a sort.</p> </div> </li> </ol> </div> </div> <div class="section" id="set-types-set-frozenset"> <span id="types-set"></span><h2>5.7. Set Types — <a class="reference internal" href="#set" title="set"><tt class="xref py py-class docutils literal"><span class="pre">set</span></tt></a>, <a class="reference internal" href="#frozenset" title="frozenset"><tt class="xref py py-class docutils literal"><span class="pre">frozenset</span></tt></a><a class="headerlink" href="#set-types-set-frozenset" title="Permalink to this headline">¶</a></h2> <p id="index-31">A <em class="dfn">set</em> object is an unordered collection of distinct <a class="reference internal" href="../glossary.html#term-hashable"><em class="xref std std-term">hashable</em></a> objects. Common uses include membership testing, removing duplicates from a sequence, and computing mathematical operations such as intersection, union, difference, and symmetric difference. (For other containers see the built in <a class="reference internal" href="#dict" title="dict"><tt class="xref py py-class docutils literal"><span class="pre">dict</span></tt></a>, <a class="reference internal" href="functions.html#list" title="list"><tt class="xref py py-class docutils literal"><span class="pre">list</span></tt></a>, and <a class="reference internal" href="functions.html#tuple" title="tuple"><tt class="xref py py-class docutils literal"><span class="pre">tuple</span></tt></a> classes, and the <a class="reference internal" href="collections.html#module-collections" title="collections: High-performance datatypes"><tt class="xref py py-mod docutils literal"><span class="pre">collections</span></tt></a> module.)</p> <p class="versionadded"> <span class="versionmodified">New in version 2.4.</span></p> <p>Like other collections, sets support <tt class="docutils literal"><span class="pre">x</span> <span class="pre">in</span> <span class="pre">set</span></tt>, <tt class="docutils literal"><span class="pre">len(set)</span></tt>, and <tt class="docutils literal"><span class="pre">for</span> <span class="pre">x</span> <span class="pre">in</span> <span class="pre">set</span></tt>. Being an unordered collection, sets do not record element position or order of insertion. Accordingly, sets do not support indexing, slicing, or other sequence-like behavior.</p> <p>There are currently two built-in set types, <a class="reference internal" href="#set" title="set"><tt class="xref py py-class docutils literal"><span class="pre">set</span></tt></a> and <a class="reference internal" href="#frozenset" title="frozenset"><tt class="xref py py-class docutils literal"><span class="pre">frozenset</span></tt></a>. The <a class="reference internal" href="#set" title="set"><tt class="xref py py-class docutils literal"><span class="pre">set</span></tt></a> type is mutable — the contents can be changed using methods like <tt class="xref py py-meth docutils literal"><span class="pre">add()</span></tt> and <tt class="xref py py-meth docutils literal"><span class="pre">remove()</span></tt>. Since it is mutable, it has no hash value and cannot be used as either a dictionary key or as an element of another set. The <a class="reference internal" href="#frozenset" title="frozenset"><tt class="xref py py-class docutils literal"><span class="pre">frozenset</span></tt></a> type is immutable and <a class="reference internal" href="../glossary.html#term-hashable"><em class="xref std std-term">hashable</em></a> — its contents cannot be altered after it is created; it can therefore be used as a dictionary key or as an element of another set.</p> <p>As of Python 2.7, non-empty sets (not frozensets) can be created by placing a comma-separated list of elements within braces, for example: <tt class="docutils literal"><span class="pre">{'jack',</span> <span class="pre">'sjoerd'}</span></tt>, in addition to the <a class="reference internal" href="#set" title="set"><tt class="xref py py-class docutils literal"><span class="pre">set</span></tt></a> constructor.</p> <p>The constructors for both classes work the same:</p> <dl class="class"> <dt id="set"> <em class="property">class </em><tt class="descname">set</tt><big>(</big><span class="optional">[</span><em>iterable</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#set" title="Permalink to this definition">¶</a></dt> <dt id="frozenset"> <em class="property">class </em><tt class="descname">frozenset</tt><big>(</big><span class="optional">[</span><em>iterable</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#frozenset" title="Permalink to this definition">¶</a></dt> <dd><p>Return a new set or frozenset object whose elements are taken from <em>iterable</em>. The elements of a set must be <a class="reference internal" href="../glossary.html#term-hashable"><em class="xref std std-term">hashable</em></a>. To represent sets of sets, the inner sets must be <a class="reference internal" href="#frozenset" title="frozenset"><tt class="xref py py-class docutils literal"><span class="pre">frozenset</span></tt></a> objects. If <em>iterable</em> is not specified, a new empty set is returned.</p> <p>Instances of <a class="reference internal" href="#set" title="set"><tt class="xref py py-class docutils literal"><span class="pre">set</span></tt></a> and <a class="reference internal" href="#frozenset" title="frozenset"><tt class="xref py py-class docutils literal"><span class="pre">frozenset</span></tt></a> provide the following operations:</p> <dl class="describe"> <dt> <tt class="descname">len(s)</tt></dt> <dd><p>Return the cardinality of set <em>s</em>.</p> </dd></dl> <dl class="describe"> <dt> <tt class="descname">x in s</tt></dt> <dd><p>Test <em>x</em> for membership in <em>s</em>.</p> </dd></dl> <dl class="describe"> <dt> <tt class="descname">x not in s</tt></dt> <dd><p>Test <em>x</em> for non-membership in <em>s</em>.</p> </dd></dl> <dl class="method"> <dt id="set.isdisjoint"> <tt class="descname">isdisjoint</tt><big>(</big><em>other</em><big>)</big><a class="headerlink" href="#set.isdisjoint" title="Permalink to this definition">¶</a></dt> <dd><p>Return True if the set has no elements in common with <em>other</em>. Sets are disjoint if and only if their intersection is the empty set.</p> <p class="versionadded"> <span class="versionmodified">New in version 2.6.</span></p> </dd></dl> <dl class="method"> <dt id="set.issubset"> <tt class="descname">issubset</tt><big>(</big><em>other</em><big>)</big><a class="headerlink" href="#set.issubset" title="Permalink to this definition">¶</a></dt> <dt> <tt class="descname">set <= other</tt></dt> <dd><p>Test whether every element in the set is in <em>other</em>.</p> </dd></dl> <dl class="method"> <dt> <tt class="descname">set < other</tt></dt> <dd><p>Test whether the set is a proper subset of <em>other</em>, that is, <tt class="docutils literal"><span class="pre">set</span> <span class="pre"><=</span> <span class="pre">other</span> <span class="pre">and</span> <span class="pre">set</span> <span class="pre">!=</span> <span class="pre">other</span></tt>.</p> </dd></dl> <dl class="method"> <dt id="set.issuperset"> <tt class="descname">issuperset</tt><big>(</big><em>other</em><big>)</big><a class="headerlink" href="#set.issuperset" title="Permalink to this definition">¶</a></dt> <dt> <tt class="descname">set >= other</tt></dt> <dd><p>Test whether every element in <em>other</em> is in the set.</p> </dd></dl> <dl class="method"> <dt> <tt class="descname">set > other</tt></dt> <dd><p>Test whether the set is a proper superset of <em>other</em>, that is, <tt class="docutils literal"><span class="pre">set</span> <span class="pre">>=</span> <span class="pre">other</span> <span class="pre">and</span> <span class="pre">set</span> <span class="pre">!=</span> <span class="pre">other</span></tt>.</p> </dd></dl> <dl class="method"> <dt id="set.union"> <tt class="descname">union</tt><big>(</big><em>other</em>, <em>...</em><big>)</big><a class="headerlink" href="#set.union" title="Permalink to this definition">¶</a></dt> <dt> <tt class="descname">set | other | ...</tt></dt> <dd><p>Return a new set with elements from the set and all others.</p> <p class="versionchanged"> <span class="versionmodified">Changed in version 2.6: </span>Accepts multiple input iterables.</p> </dd></dl> <dl class="method"> <dt id="set.intersection"> <tt class="descname">intersection</tt><big>(</big><em>other</em>, <em>...</em><big>)</big><a class="headerlink" href="#set.intersection" title="Permalink to this definition">¶</a></dt> <dt> <tt class="descname">set & other & ...</tt></dt> <dd><p>Return a new set with elements common to the set and all others.</p> <p class="versionchanged"> <span class="versionmodified">Changed in version 2.6: </span>Accepts multiple input iterables.</p> </dd></dl> <dl class="method"> <dt id="set.difference"> <tt class="descname">difference</tt><big>(</big><em>other</em>, <em>...</em><big>)</big><a class="headerlink" href="#set.difference" title="Permalink to this definition">¶</a></dt> <dt> <tt class="descname">set - other - ...</tt></dt> <dd><p>Return a new set with elements in the set that are not in the others.</p> <p class="versionchanged"> <span class="versionmodified">Changed in version 2.6: </span>Accepts multiple input iterables.</p> </dd></dl> <dl class="method"> <dt id="set.symmetric_difference"> <tt class="descname">symmetric_difference</tt><big>(</big><em>other</em><big>)</big><a class="headerlink" href="#set.symmetric_difference" title="Permalink to this definition">¶</a></dt> <dt> <tt class="descname">set ^ other</tt></dt> <dd><p>Return a new set with elements in either the set or <em>other</em> but not both.</p> </dd></dl> <dl class="method"> <dt id="set.copy"> <tt class="descname">copy</tt><big>(</big><big>)</big><a class="headerlink" href="#set.copy" title="Permalink to this definition">¶</a></dt> <dd><p>Return a new set with a shallow copy of <em>s</em>.</p> </dd></dl> <p>Note, the non-operator versions of <a class="reference internal" href="#set.union" title="set.union"><tt class="xref py py-meth docutils literal"><span class="pre">union()</span></tt></a>, <a class="reference internal" href="#set.intersection" title="set.intersection"><tt class="xref py py-meth docutils literal"><span class="pre">intersection()</span></tt></a>, <a class="reference internal" href="#set.difference" title="set.difference"><tt class="xref py py-meth docutils literal"><span class="pre">difference()</span></tt></a>, and <a class="reference internal" href="#set.symmetric_difference" title="set.symmetric_difference"><tt class="xref py py-meth docutils literal"><span class="pre">symmetric_difference()</span></tt></a>, <a class="reference internal" href="#set.issubset" title="set.issubset"><tt class="xref py py-meth docutils literal"><span class="pre">issubset()</span></tt></a>, and <a class="reference internal" href="#set.issuperset" title="set.issuperset"><tt class="xref py py-meth docutils literal"><span class="pre">issuperset()</span></tt></a> methods will accept any iterable as an argument. In contrast, their operator based counterparts require their arguments to be sets. This precludes error-prone constructions like <tt class="docutils literal"><span class="pre">set('abc')</span> <span class="pre">&</span> <span class="pre">'cbs'</span></tt> in favor of the more readable <tt class="docutils literal"><span class="pre">set('abc').intersection('cbs')</span></tt>.</p> <p>Both <a class="reference internal" href="#set" title="set"><tt class="xref py py-class docutils literal"><span class="pre">set</span></tt></a> and <a class="reference internal" href="#frozenset" title="frozenset"><tt class="xref py py-class docutils literal"><span class="pre">frozenset</span></tt></a> support set to set comparisons. Two sets are equal if and only if every element of each set is contained in the other (each is a subset of the other). A set is less than another set if and only if the first set is a proper subset of the second set (is a subset, but is not equal). A set is greater than another set if and only if the first set is a proper superset of the second set (is a superset, but is not equal).</p> <p>Instances of <a class="reference internal" href="#set" title="set"><tt class="xref py py-class docutils literal"><span class="pre">set</span></tt></a> are compared to instances of <a class="reference internal" href="#frozenset" title="frozenset"><tt class="xref py py-class docutils literal"><span class="pre">frozenset</span></tt></a> based on their members. For example, <tt class="docutils literal"><span class="pre">set('abc')</span> <span class="pre">==</span> <span class="pre">frozenset('abc')</span></tt> returns <tt class="docutils literal"><span class="pre">True</span></tt> and so does <tt class="docutils literal"><span class="pre">set('abc')</span> <span class="pre">in</span> <span class="pre">set([frozenset('abc')])</span></tt>.</p> <p>The subset and equality comparisons do not generalize to a total ordering function. For example, any two non-empty disjoint sets are not equal and are not subsets of each other, so <em>all</em> of the following return <tt class="docutils literal"><span class="pre">False</span></tt>: <tt class="docutils literal"><span class="pre">a<b</span></tt>, <tt class="docutils literal"><span class="pre">a==b</span></tt>, or <tt class="docutils literal"><span class="pre">a>b</span></tt>. Accordingly, sets do not implement the <a class="reference internal" href="../reference/datamodel.html#object.__cmp__" title="object.__cmp__"><tt class="xref py py-meth docutils literal"><span class="pre">__cmp__()</span></tt></a> method.</p> <p>Since sets only define partial ordering (subset relationships), the output of the <tt class="xref py py-meth docutils literal"><span class="pre">list.sort()</span></tt> method is undefined for lists of sets.</p> <p>Set elements, like dictionary keys, must be <a class="reference internal" href="../glossary.html#term-hashable"><em class="xref std std-term">hashable</em></a>.</p> <p>Binary operations that mix <a class="reference internal" href="#set" title="set"><tt class="xref py py-class docutils literal"><span class="pre">set</span></tt></a> instances with <a class="reference internal" href="#frozenset" title="frozenset"><tt class="xref py py-class docutils literal"><span class="pre">frozenset</span></tt></a> return the type of the first operand. For example: <tt class="docutils literal"><span class="pre">frozenset('ab')</span> <span class="pre">|</span> <span class="pre">set('bc')</span></tt> returns an instance of <a class="reference internal" href="#frozenset" title="frozenset"><tt class="xref py py-class docutils literal"><span class="pre">frozenset</span></tt></a>.</p> <p>The following table lists operations available for <a class="reference internal" href="#set" title="set"><tt class="xref py py-class docutils literal"><span class="pre">set</span></tt></a> that do not apply to immutable instances of <a class="reference internal" href="#frozenset" title="frozenset"><tt class="xref py py-class docutils literal"><span class="pre">frozenset</span></tt></a>:</p> <dl class="method"> <dt id="set.update"> <tt class="descname">update</tt><big>(</big><em>other</em>, <em>...</em><big>)</big><a class="headerlink" href="#set.update" title="Permalink to this definition">¶</a></dt> <dt> <tt class="descname">set |= other | ...</tt></dt> <dd><p>Update the set, adding elements from all others.</p> <p class="versionchanged"> <span class="versionmodified">Changed in version 2.6: </span>Accepts multiple input iterables.</p> </dd></dl> <dl class="method"> <dt id="set.intersection_update"> <tt class="descname">intersection_update</tt><big>(</big><em>other</em>, <em>...</em><big>)</big><a class="headerlink" href="#set.intersection_update" title="Permalink to this definition">¶</a></dt> <dt> <tt class="descname">set &= other & ...</tt></dt> <dd><p>Update the set, keeping only elements found in it and all others.</p> <p class="versionchanged"> <span class="versionmodified">Changed in version 2.6: </span>Accepts multiple input iterables.</p> </dd></dl> <dl class="method"> <dt id="set.difference_update"> <tt class="descname">difference_update</tt><big>(</big><em>other</em>, <em>...</em><big>)</big><a class="headerlink" href="#set.difference_update" title="Permalink to this definition">¶</a></dt> <dt> <tt class="descname">set -= other | ...</tt></dt> <dd><p>Update the set, removing elements found in others.</p> <p class="versionchanged"> <span class="versionmodified">Changed in version 2.6: </span>Accepts multiple input iterables.</p> </dd></dl> <dl class="method"> <dt id="set.symmetric_difference_update"> <tt class="descname">symmetric_difference_update</tt><big>(</big><em>other</em><big>)</big><a class="headerlink" href="#set.symmetric_difference_update" title="Permalink to this definition">¶</a></dt> <dt> <tt class="descname">set ^= other</tt></dt> <dd><p>Update the set, keeping only elements found in either set, but not in both.</p> </dd></dl> <dl class="method"> <dt id="set.add"> <tt class="descname">add</tt><big>(</big><em>elem</em><big>)</big><a class="headerlink" href="#set.add" title="Permalink to this definition">¶</a></dt> <dd><p>Add element <em>elem</em> to the set.</p> </dd></dl> <dl class="method"> <dt id="set.remove"> <tt class="descname">remove</tt><big>(</big><em>elem</em><big>)</big><a class="headerlink" href="#set.remove" title="Permalink to this definition">¶</a></dt> <dd><p>Remove element <em>elem</em> from the set. Raises <a class="reference internal" href="exceptions.html#exceptions.KeyError" title="exceptions.KeyError"><tt class="xref py py-exc docutils literal"><span class="pre">KeyError</span></tt></a> if <em>elem</em> is not contained in the set.</p> </dd></dl> <dl class="method"> <dt id="set.discard"> <tt class="descname">discard</tt><big>(</big><em>elem</em><big>)</big><a class="headerlink" href="#set.discard" title="Permalink to this definition">¶</a></dt> <dd><p>Remove element <em>elem</em> from the set if it is present.</p> </dd></dl> <dl class="method"> <dt id="set.pop"> <tt class="descname">pop</tt><big>(</big><big>)</big><a class="headerlink" href="#set.pop" title="Permalink to this definition">¶</a></dt> <dd><p>Remove and return an arbitrary element from the set. Raises <a class="reference internal" href="exceptions.html#exceptions.KeyError" title="exceptions.KeyError"><tt class="xref py py-exc docutils literal"><span class="pre">KeyError</span></tt></a> if the set is empty.</p> </dd></dl> <dl class="method"> <dt id="set.clear"> <tt class="descname">clear</tt><big>(</big><big>)</big><a class="headerlink" href="#set.clear" title="Permalink to this definition">¶</a></dt> <dd><p>Remove all elements from the set.</p> </dd></dl> <p>Note, the non-operator versions of the <a class="reference internal" href="#set.update" title="set.update"><tt class="xref py py-meth docutils literal"><span class="pre">update()</span></tt></a>, <a class="reference internal" href="#set.intersection_update" title="set.intersection_update"><tt class="xref py py-meth docutils literal"><span class="pre">intersection_update()</span></tt></a>, <a class="reference internal" href="#set.difference_update" title="set.difference_update"><tt class="xref py py-meth docutils literal"><span class="pre">difference_update()</span></tt></a>, and <a class="reference internal" href="#set.symmetric_difference_update" title="set.symmetric_difference_update"><tt class="xref py py-meth docutils literal"><span class="pre">symmetric_difference_update()</span></tt></a> methods will accept any iterable as an argument.</p> <p>Note, the <em>elem</em> argument to the <a class="reference internal" href="../reference/datamodel.html#object.__contains__" title="object.__contains__"><tt class="xref py py-meth docutils literal"><span class="pre">__contains__()</span></tt></a>, <a class="reference internal" href="#set.remove" title="set.remove"><tt class="xref py py-meth docutils literal"><span class="pre">remove()</span></tt></a>, and <a class="reference internal" href="#set.discard" title="set.discard"><tt class="xref py py-meth docutils literal"><span class="pre">discard()</span></tt></a> methods may be a set. To support searching for an equivalent frozenset, the <em>elem</em> set is temporarily mutated during the search and then restored. During the search, the <em>elem</em> set should not be read or mutated since it does not have a meaningful value.</p> </dd></dl> <div class="admonition-see-also admonition seealso"> <p class="first admonition-title">See also</p> <dl class="last docutils"> <dt><a class="reference internal" href="sets.html#comparison-to-builtin-set"><em>Comparison to the built-in set types</em></a></dt> <dd>Differences between the <a class="reference internal" href="sets.html#module-sets" title="sets: Implementation of sets of unique elements. (deprecated)"><tt class="xref py py-mod docutils literal"><span class="pre">sets</span></tt></a> module and the built-in set types.</dd> </dl> </div> </div> <div class="section" id="mapping-types-dict"> <span id="typesmapping"></span><h2>5.8. Mapping Types — <a class="reference internal" href="#dict" title="dict"><tt class="xref py py-class docutils literal"><span class="pre">dict</span></tt></a><a class="headerlink" href="#mapping-types-dict" title="Permalink to this headline">¶</a></h2> <p id="index-32">A <a class="reference internal" href="../glossary.html#term-mapping"><em class="xref std std-term">mapping</em></a> object maps <a class="reference internal" href="../glossary.html#term-hashable"><em class="xref std std-term">hashable</em></a> values to arbitrary objects. Mappings are mutable objects. There is currently only one standard mapping type, the <em class="dfn">dictionary</em>. (For other containers see the built in <a class="reference internal" href="functions.html#list" title="list"><tt class="xref py py-class docutils literal"><span class="pre">list</span></tt></a>, <a class="reference internal" href="#set" title="set"><tt class="xref py py-class docutils literal"><span class="pre">set</span></tt></a>, and <a class="reference internal" href="functions.html#tuple" title="tuple"><tt class="xref py py-class docutils literal"><span class="pre">tuple</span></tt></a> classes, and the <a class="reference internal" href="collections.html#module-collections" title="collections: High-performance datatypes"><tt class="xref py py-mod docutils literal"><span class="pre">collections</span></tt></a> module.)</p> <p>A dictionary’s keys are <em>almost</em> arbitrary values. Values that are not <a class="reference internal" href="../glossary.html#term-hashable"><em class="xref std std-term">hashable</em></a>, that is, values containing lists, dictionaries or other mutable types (that are compared by value rather than by object identity) may not be used as keys. Numeric types used for keys obey the normal rules for numeric comparison: if two numbers compare equal (such as <tt class="docutils literal"><span class="pre">1</span></tt> and <tt class="docutils literal"><span class="pre">1.0</span></tt>) then they can be used interchangeably to index the same dictionary entry. (Note however, that since computers store floating-point numbers as approximations it is usually unwise to use them as dictionary keys.)</p> <p>Dictionaries can be created by placing a comma-separated list of <tt class="docutils literal"><span class="pre">key:</span> <span class="pre">value</span></tt> pairs within braces, for example: <tt class="docutils literal"><span class="pre">{'jack':</span> <span class="pre">4098,</span> <span class="pre">'sjoerd':</span> <span class="pre">4127}</span></tt> or <tt class="docutils literal"><span class="pre">{4098:</span> <span class="pre">'jack',</span> <span class="pre">4127:</span> <span class="pre">'sjoerd'}</span></tt>, or by the <a class="reference internal" href="#dict" title="dict"><tt class="xref py py-class docutils literal"><span class="pre">dict</span></tt></a> constructor.</p> <dl class="class"> <dt id="dict"> <em class="property">class </em><tt class="descname">dict</tt><big>(</big><em>**kwarg</em><big>)</big><a class="headerlink" href="#dict" title="Permalink to this definition">¶</a></dt> <dt> <em class="property">class </em><tt class="descname">dict</tt><big>(</big><em>mapping</em>, <em>**kwarg</em><big>)</big></dt> <dt> <em class="property">class </em><tt class="descname">dict</tt><big>(</big><em>iterable</em>, <em>**kwarg</em><big>)</big></dt> <dd><p>Return a new dictionary initialized from an optional positional argument and a possibly empty set of keyword arguments.</p> <p>If no positional argument is given, an empty dictionary is created. If a positional argument is given and it is a mapping object, a dictionary is created with the same key-value pairs as the mapping object. Otherwise, the positional argument must be an <a class="reference internal" href="../glossary.html#term-iterator"><em class="xref std std-term">iterator</em></a> object. Each item in the iterable must itself be an iterator with exactly two objects. The first object of each item becomes a key in the new dictionary, and the second object the corresponding value. If a key occurs more than once, the last value for that key becomes the corresponding value in the new dictionary.</p> <p>If keyword arguments are given, the keyword arguments and their values are added to the dictionary created from the positional argument. If a key being added is already present, the value from the keyword argument replaces the value from the positional argument.</p> <p>To illustrate, the following examples all return a dictionary equal to <tt class="docutils literal"><span class="pre">{"one":</span> <span class="pre">1,</span> <span class="pre">"two":</span> <span class="pre">2,</span> <span class="pre">"three":</span> <span class="pre">3}</span></tt>:</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">a</span> <span class="o">=</span> <span class="nb">dict</span><span class="p">(</span><span class="n">one</span><span class="o">=</span><span class="mi">1</span><span class="p">,</span> <span class="n">two</span><span class="o">=</span><span class="mi">2</span><span class="p">,</span> <span class="n">three</span><span class="o">=</span><span class="mi">3</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">b</span> <span class="o">=</span> <span class="p">{</span><span class="s">'one'</span><span class="p">:</span> <span class="mi">1</span><span class="p">,</span> <span class="s">'two'</span><span class="p">:</span> <span class="mi">2</span><span class="p">,</span> <span class="s">'three'</span><span class="p">:</span> <span class="mi">3</span><span class="p">}</span> <span class="gp">>>> </span><span class="n">c</span> <span class="o">=</span> <span class="nb">dict</span><span class="p">(</span><span class="nb">zip</span><span class="p">([</span><span class="s">'one'</span><span class="p">,</span> <span class="s">'two'</span><span class="p">,</span> <span class="s">'three'</span><span class="p">],</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">]))</span> <span class="gp">>>> </span><span class="n">d</span> <span class="o">=</span> <span class="nb">dict</span><span class="p">([(</span><span class="s">'two'</span><span class="p">,</span> <span class="mi">2</span><span class="p">),</span> <span class="p">(</span><span class="s">'one'</span><span class="p">,</span> <span class="mi">1</span><span class="p">),</span> <span class="p">(</span><span class="s">'three'</span><span class="p">,</span> <span class="mi">3</span><span class="p">)])</span> <span class="gp">>>> </span><span class="n">e</span> <span class="o">=</span> <span class="nb">dict</span><span class="p">({</span><span class="s">'three'</span><span class="p">:</span> <span class="mi">3</span><span class="p">,</span> <span class="s">'one'</span><span class="p">:</span> <span class="mi">1</span><span class="p">,</span> <span class="s">'two'</span><span class="p">:</span> <span class="mi">2</span><span class="p">})</span> <span class="gp">>>> </span><span class="n">a</span> <span class="o">==</span> <span class="n">b</span> <span class="o">==</span> <span class="n">c</span> <span class="o">==</span> <span class="n">d</span> <span class="o">==</span> <span class="n">e</span> <span class="go">True</span> </pre></div> </div> <p>Providing keyword arguments as in the first example only works for keys that are valid Python identifiers. Otherwise, any valid keys can be used.</p> <p class="versionadded"> <span class="versionmodified">New in version 2.2.</span></p> <p class="versionchanged"> <span class="versionmodified">Changed in version 2.3: </span>Support for building a dictionary from keyword arguments added.</p> <p>These are the operations that dictionaries support (and therefore, custom mapping types should support too):</p> <dl class="describe"> <dt> <tt class="descname">len(d)</tt></dt> <dd><p>Return the number of items in the dictionary <em>d</em>.</p> </dd></dl> <dl class="describe"> <dt> <tt class="descname">d[key]</tt></dt> <dd><p>Return the item of <em>d</em> with key <em>key</em>. Raises a <a class="reference internal" href="exceptions.html#exceptions.KeyError" title="exceptions.KeyError"><tt class="xref py py-exc docutils literal"><span class="pre">KeyError</span></tt></a> if <em>key</em> is not in the map.</p> <p class="versionadded"> <span class="versionmodified">New in version 2.5: </span>If a subclass of dict defines a method <tt class="xref py py-meth docutils literal"><span class="pre">__missing__()</span></tt>, if the key <em>key</em> is not present, the <tt class="docutils literal"><span class="pre">d[key]</span></tt> operation calls that method with the key <em>key</em> as argument. The <tt class="docutils literal"><span class="pre">d[key]</span></tt> operation then returns or raises whatever is returned or raised by the <tt class="docutils literal"><span class="pre">__missing__(key)</span></tt> call if the key is not present. No other operations or methods invoke <tt class="xref py py-meth docutils literal"><span class="pre">__missing__()</span></tt>. If <tt class="xref py py-meth docutils literal"><span class="pre">__missing__()</span></tt> is not defined, <a class="reference internal" href="exceptions.html#exceptions.KeyError" title="exceptions.KeyError"><tt class="xref py py-exc docutils literal"><span class="pre">KeyError</span></tt></a> is raised. <tt class="xref py py-meth docutils literal"><span class="pre">__missing__()</span></tt> must be a method; it cannot be an instance variable. For an example, see <a class="reference internal" href="collections.html#collections.defaultdict" title="collections.defaultdict"><tt class="xref py py-class docutils literal"><span class="pre">collections.defaultdict</span></tt></a>.</p> </dd></dl> <dl class="describe"> <dt> <tt class="descname">d[key] = value</tt></dt> <dd><p>Set <tt class="docutils literal"><span class="pre">d[key]</span></tt> to <em>value</em>.</p> </dd></dl> <dl class="describe"> <dt> <tt class="descname">del d[key]</tt></dt> <dd><p>Remove <tt class="docutils literal"><span class="pre">d[key]</span></tt> from <em>d</em>. Raises a <a class="reference internal" href="exceptions.html#exceptions.KeyError" title="exceptions.KeyError"><tt class="xref py py-exc docutils literal"><span class="pre">KeyError</span></tt></a> if <em>key</em> is not in the map.</p> </dd></dl> <dl class="describe"> <dt> <tt class="descname">key in d</tt></dt> <dd><p>Return <tt class="docutils literal"><span class="pre">True</span></tt> if <em>d</em> has a key <em>key</em>, else <tt class="docutils literal"><span class="pre">False</span></tt>.</p> <p class="versionadded"> <span class="versionmodified">New in version 2.2.</span></p> </dd></dl> <dl class="describe"> <dt> <tt class="descname">key not in d</tt></dt> <dd><p>Equivalent to <tt class="docutils literal"><span class="pre">not</span> <span class="pre">key</span> <span class="pre">in</span> <span class="pre">d</span></tt>.</p> <p class="versionadded"> <span class="versionmodified">New in version 2.2.</span></p> </dd></dl> <dl class="describe"> <dt> <tt class="descname">iter(d)</tt></dt> <dd><p>Return an iterator over the keys of the dictionary. This is a shortcut for <a class="reference internal" href="#dict.iterkeys" title="dict.iterkeys"><tt class="xref py py-meth docutils literal"><span class="pre">iterkeys()</span></tt></a>.</p> </dd></dl> <dl class="method"> <dt id="dict.clear"> <tt class="descname">clear</tt><big>(</big><big>)</big><a class="headerlink" href="#dict.clear" title="Permalink to this definition">¶</a></dt> <dd><p>Remove all items from the dictionary.</p> </dd></dl> <dl class="method"> <dt id="dict.copy"> <tt class="descname">copy</tt><big>(</big><big>)</big><a class="headerlink" href="#dict.copy" title="Permalink to this definition">¶</a></dt> <dd><p>Return a shallow copy of the dictionary.</p> </dd></dl> <dl class="method"> <dt id="dict.fromkeys"> <tt class="descname">fromkeys</tt><big>(</big><em>seq</em><span class="optional">[</span>, <em>value</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#dict.fromkeys" title="Permalink to this definition">¶</a></dt> <dd><p>Create a new dictionary with keys from <em>seq</em> and values set to <em>value</em>.</p> <p><a class="reference internal" href="#dict.fromkeys" title="dict.fromkeys"><tt class="xref py py-func docutils literal"><span class="pre">fromkeys()</span></tt></a> is a class method that returns a new dictionary. <em>value</em> defaults to <tt class="docutils literal"><span class="pre">None</span></tt>.</p> <p class="versionadded"> <span class="versionmodified">New in version 2.3.</span></p> </dd></dl> <dl class="method"> <dt id="dict.get"> <tt class="descname">get</tt><big>(</big><em>key</em><span class="optional">[</span>, <em>default</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#dict.get" title="Permalink to this definition">¶</a></dt> <dd><p>Return the value for <em>key</em> if <em>key</em> is in the dictionary, else <em>default</em>. If <em>default</em> is not given, it defaults to <tt class="docutils literal"><span class="pre">None</span></tt>, so that this method never raises a <a class="reference internal" href="exceptions.html#exceptions.KeyError" title="exceptions.KeyError"><tt class="xref py py-exc docutils literal"><span class="pre">KeyError</span></tt></a>.</p> </dd></dl> <dl class="method"> <dt id="dict.has_key"> <tt class="descname">has_key</tt><big>(</big><em>key</em><big>)</big><a class="headerlink" href="#dict.has_key" title="Permalink to this definition">¶</a></dt> <dd><p>Test for the presence of <em>key</em> in the dictionary. <a class="reference internal" href="#dict.has_key" title="dict.has_key"><tt class="xref py py-meth docutils literal"><span class="pre">has_key()</span></tt></a> is deprecated in favor of <tt class="docutils literal"><span class="pre">key</span> <span class="pre">in</span> <span class="pre">d</span></tt>.</p> </dd></dl> <dl class="method"> <dt id="dict.items"> <tt class="descname">items</tt><big>(</big><big>)</big><a class="headerlink" href="#dict.items" title="Permalink to this definition">¶</a></dt> <dd><p>Return a copy of the dictionary’s list of <tt class="docutils literal"><span class="pre">(key,</span> <span class="pre">value)</span></tt> pairs.</p> <div class="impl-detail compound"> <p><strong>CPython implementation detail:</strong> Keys and values are listed in an arbitrary order which is non-random, varies across Python implementations, and depends on the dictionary’s history of insertions and deletions.</p> </div> <p>If <a class="reference internal" href="#dict.items" title="dict.items"><tt class="xref py py-meth docutils literal"><span class="pre">items()</span></tt></a>, <a class="reference internal" href="#dict.keys" title="dict.keys"><tt class="xref py py-meth docutils literal"><span class="pre">keys()</span></tt></a>, <a class="reference internal" href="#dict.values" title="dict.values"><tt class="xref py py-meth docutils literal"><span class="pre">values()</span></tt></a>, <a class="reference internal" href="#dict.iteritems" title="dict.iteritems"><tt class="xref py py-meth docutils literal"><span class="pre">iteritems()</span></tt></a>, <a class="reference internal" href="#dict.iterkeys" title="dict.iterkeys"><tt class="xref py py-meth docutils literal"><span class="pre">iterkeys()</span></tt></a>, and <a class="reference internal" href="#dict.itervalues" title="dict.itervalues"><tt class="xref py py-meth docutils literal"><span class="pre">itervalues()</span></tt></a> are called with no intervening modifications to the dictionary, the lists will directly correspond. This allows the creation of <tt class="docutils literal"><span class="pre">(value,</span> <span class="pre">key)</span></tt> pairs using <a class="reference internal" href="functions.html#zip" title="zip"><tt class="xref py py-func docutils literal"><span class="pre">zip()</span></tt></a>: <tt class="docutils literal"><span class="pre">pairs</span> <span class="pre">=</span> <span class="pre">zip(d.values(),</span> <span class="pre">d.keys())</span></tt>. The same relationship holds for the <a class="reference internal" href="#dict.iterkeys" title="dict.iterkeys"><tt class="xref py py-meth docutils literal"><span class="pre">iterkeys()</span></tt></a> and <a class="reference internal" href="#dict.itervalues" title="dict.itervalues"><tt class="xref py py-meth docutils literal"><span class="pre">itervalues()</span></tt></a> methods: <tt class="docutils literal"><span class="pre">pairs</span> <span class="pre">=</span> <span class="pre">zip(d.itervalues(),</span> <span class="pre">d.iterkeys())</span></tt> provides the same value for <tt class="docutils literal"><span class="pre">pairs</span></tt>. Another way to create the same list is <tt class="docutils literal"><span class="pre">pairs</span> <span class="pre">=</span> <span class="pre">[(v,</span> <span class="pre">k)</span> <span class="pre">for</span> <span class="pre">(k,</span> <span class="pre">v)</span> <span class="pre">in</span> <span class="pre">d.iteritems()]</span></tt>.</p> </dd></dl> <dl class="method"> <dt id="dict.iteritems"> <tt class="descname">iteritems</tt><big>(</big><big>)</big><a class="headerlink" href="#dict.iteritems" title="Permalink to this definition">¶</a></dt> <dd><p>Return an iterator over the dictionary’s <tt class="docutils literal"><span class="pre">(key,</span> <span class="pre">value)</span></tt> pairs. See the note for <a class="reference internal" href="#dict.items" title="dict.items"><tt class="xref py py-meth docutils literal"><span class="pre">dict.items()</span></tt></a>.</p> <p>Using <a class="reference internal" href="#dict.iteritems" title="dict.iteritems"><tt class="xref py py-meth docutils literal"><span class="pre">iteritems()</span></tt></a> while adding or deleting entries in the dictionary may raise a <a class="reference internal" href="exceptions.html#exceptions.RuntimeError" title="exceptions.RuntimeError"><tt class="xref py py-exc docutils literal"><span class="pre">RuntimeError</span></tt></a> or fail to iterate over all entries.</p> <p class="versionadded"> <span class="versionmodified">New in version 2.2.</span></p> </dd></dl> <dl class="method"> <dt id="dict.iterkeys"> <tt class="descname">iterkeys</tt><big>(</big><big>)</big><a class="headerlink" href="#dict.iterkeys" title="Permalink to this definition">¶</a></dt> <dd><p>Return an iterator over the dictionary’s keys. See the note for <a class="reference internal" href="#dict.items" title="dict.items"><tt class="xref py py-meth docutils literal"><span class="pre">dict.items()</span></tt></a>.</p> <p>Using <a class="reference internal" href="#dict.iterkeys" title="dict.iterkeys"><tt class="xref py py-meth docutils literal"><span class="pre">iterkeys()</span></tt></a> while adding or deleting entries in the dictionary may raise a <a class="reference internal" href="exceptions.html#exceptions.RuntimeError" title="exceptions.RuntimeError"><tt class="xref py py-exc docutils literal"><span class="pre">RuntimeError</span></tt></a> or fail to iterate over all entries.</p> <p class="versionadded"> <span class="versionmodified">New in version 2.2.</span></p> </dd></dl> <dl class="method"> <dt id="dict.itervalues"> <tt class="descname">itervalues</tt><big>(</big><big>)</big><a class="headerlink" href="#dict.itervalues" title="Permalink to this definition">¶</a></dt> <dd><p>Return an iterator over the dictionary’s values. See the note for <a class="reference internal" href="#dict.items" title="dict.items"><tt class="xref py py-meth docutils literal"><span class="pre">dict.items()</span></tt></a>.</p> <p>Using <a class="reference internal" href="#dict.itervalues" title="dict.itervalues"><tt class="xref py py-meth docutils literal"><span class="pre">itervalues()</span></tt></a> while adding or deleting entries in the dictionary may raise a <a class="reference internal" href="exceptions.html#exceptions.RuntimeError" title="exceptions.RuntimeError"><tt class="xref py py-exc docutils literal"><span class="pre">RuntimeError</span></tt></a> or fail to iterate over all entries.</p> <p class="versionadded"> <span class="versionmodified">New in version 2.2.</span></p> </dd></dl> <dl class="method"> <dt id="dict.keys"> <tt class="descname">keys</tt><big>(</big><big>)</big><a class="headerlink" href="#dict.keys" title="Permalink to this definition">¶</a></dt> <dd><p>Return a copy of the dictionary’s list of keys. See the note for <a class="reference internal" href="#dict.items" title="dict.items"><tt class="xref py py-meth docutils literal"><span class="pre">dict.items()</span></tt></a>.</p> </dd></dl> <dl class="method"> <dt id="dict.pop"> <tt class="descname">pop</tt><big>(</big><em>key</em><span class="optional">[</span>, <em>default</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#dict.pop" title="Permalink to this definition">¶</a></dt> <dd><p>If <em>key</em> is in the dictionary, remove it and return its value, else return <em>default</em>. If <em>default</em> is not given and <em>key</em> is not in the dictionary, a <a class="reference internal" href="exceptions.html#exceptions.KeyError" title="exceptions.KeyError"><tt class="xref py py-exc docutils literal"><span class="pre">KeyError</span></tt></a> is raised.</p> <p class="versionadded"> <span class="versionmodified">New in version 2.3.</span></p> </dd></dl> <dl class="method"> <dt id="dict.popitem"> <tt class="descname">popitem</tt><big>(</big><big>)</big><a class="headerlink" href="#dict.popitem" title="Permalink to this definition">¶</a></dt> <dd><p>Remove and return an arbitrary <tt class="docutils literal"><span class="pre">(key,</span> <span class="pre">value)</span></tt> pair from the dictionary.</p> <p><a class="reference internal" href="#dict.popitem" title="dict.popitem"><tt class="xref py py-func docutils literal"><span class="pre">popitem()</span></tt></a> is useful to destructively iterate over a dictionary, as often used in set algorithms. If the dictionary is empty, calling <a class="reference internal" href="#dict.popitem" title="dict.popitem"><tt class="xref py py-func docutils literal"><span class="pre">popitem()</span></tt></a> raises a <a class="reference internal" href="exceptions.html#exceptions.KeyError" title="exceptions.KeyError"><tt class="xref py py-exc docutils literal"><span class="pre">KeyError</span></tt></a>.</p> </dd></dl> <dl class="method"> <dt id="dict.setdefault"> <tt class="descname">setdefault</tt><big>(</big><em>key</em><span class="optional">[</span>, <em>default</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#dict.setdefault" title="Permalink to this definition">¶</a></dt> <dd><p>If <em>key</em> is in the dictionary, return its value. If not, insert <em>key</em> with a value of <em>default</em> and return <em>default</em>. <em>default</em> defaults to <tt class="docutils literal"><span class="pre">None</span></tt>.</p> </dd></dl> <dl class="method"> <dt id="dict.update"> <tt class="descname">update</tt><big>(</big><span class="optional">[</span><em>other</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#dict.update" title="Permalink to this definition">¶</a></dt> <dd><p>Update the dictionary with the key/value pairs from <em>other</em>, overwriting existing keys. Return <tt class="docutils literal"><span class="pre">None</span></tt>.</p> <p><a class="reference internal" href="#dict.update" title="dict.update"><tt class="xref py py-func docutils literal"><span class="pre">update()</span></tt></a> accepts either another dictionary object or an iterable of key/value pairs (as tuples or other iterables of length two). If keyword arguments are specified, the dictionary is then updated with those key/value pairs: <tt class="docutils literal"><span class="pre">d.update(red=1,</span> <span class="pre">blue=2)</span></tt>.</p> <p class="versionchanged"> <span class="versionmodified">Changed in version 2.4: </span>Allowed the argument to be an iterable of key/value pairs and allowed keyword arguments.</p> </dd></dl> <dl class="method"> <dt id="dict.values"> <tt class="descname">values</tt><big>(</big><big>)</big><a class="headerlink" href="#dict.values" title="Permalink to this definition">¶</a></dt> <dd><p>Return a copy of the dictionary’s list of values. See the note for <a class="reference internal" href="#dict.items" title="dict.items"><tt class="xref py py-meth docutils literal"><span class="pre">dict.items()</span></tt></a>.</p> </dd></dl> <dl class="method"> <dt id="dict.viewitems"> <tt class="descname">viewitems</tt><big>(</big><big>)</big><a class="headerlink" href="#dict.viewitems" title="Permalink to this definition">¶</a></dt> <dd><p>Return a new view of the dictionary’s items (<tt class="docutils literal"><span class="pre">(key,</span> <span class="pre">value)</span></tt> pairs). See below for documentation of view objects.</p> <p class="versionadded"> <span class="versionmodified">New in version 2.7.</span></p> </dd></dl> <dl class="method"> <dt id="dict.viewkeys"> <tt class="descname">viewkeys</tt><big>(</big><big>)</big><a class="headerlink" href="#dict.viewkeys" title="Permalink to this definition">¶</a></dt> <dd><p>Return a new view of the dictionary’s keys. See below for documentation of view objects.</p> <p class="versionadded"> <span class="versionmodified">New in version 2.7.</span></p> </dd></dl> <dl class="method"> <dt id="dict.viewvalues"> <tt class="descname">viewvalues</tt><big>(</big><big>)</big><a class="headerlink" href="#dict.viewvalues" title="Permalink to this definition">¶</a></dt> <dd><p>Return a new view of the dictionary’s values. See below for documentation of view objects.</p> <p class="versionadded"> <span class="versionmodified">New in version 2.7.</span></p> </dd></dl> </dd></dl> <div class="section" id="dictionary-view-objects"> <span id="dict-views"></span><h3>5.8.1. Dictionary view objects<a class="headerlink" href="#dictionary-view-objects" title="Permalink to this headline">¶</a></h3> <p>The objects returned by <a class="reference internal" href="#dict.viewkeys" title="dict.viewkeys"><tt class="xref py py-meth docutils literal"><span class="pre">dict.viewkeys()</span></tt></a>, <a class="reference internal" href="#dict.viewvalues" title="dict.viewvalues"><tt class="xref py py-meth docutils literal"><span class="pre">dict.viewvalues()</span></tt></a> and <a class="reference internal" href="#dict.viewitems" title="dict.viewitems"><tt class="xref py py-meth docutils literal"><span class="pre">dict.viewitems()</span></tt></a> are <em>view objects</em>. They provide a dynamic view on the dictionary’s entries, which means that when the dictionary changes, the view reflects these changes.</p> <p>Dictionary views can be iterated over to yield their respective data, and support membership tests:</p> <dl class="describe"> <dt> <tt class="descname">len(dictview)</tt></dt> <dd><p>Return the number of entries in the dictionary.</p> </dd></dl> <dl class="describe"> <dt> <tt class="descname">iter(dictview)</tt></dt> <dd><p>Return an iterator over the keys, values or items (represented as tuples of <tt class="docutils literal"><span class="pre">(key,</span> <span class="pre">value)</span></tt>) in the dictionary.</p> <p>Keys and values are iterated over in an arbitrary order which is non-random, varies across Python implementations, and depends on the dictionary’s history of insertions and deletions. If keys, values and items views are iterated over with no intervening modifications to the dictionary, the order of items will directly correspond. This allows the creation of <tt class="docutils literal"><span class="pre">(value,</span> <span class="pre">key)</span></tt> pairs using <a class="reference internal" href="functions.html#zip" title="zip"><tt class="xref py py-func docutils literal"><span class="pre">zip()</span></tt></a>: <tt class="docutils literal"><span class="pre">pairs</span> <span class="pre">=</span> <span class="pre">zip(d.values(),</span> <span class="pre">d.keys())</span></tt>. Another way to create the same list is <tt class="docutils literal"><span class="pre">pairs</span> <span class="pre">=</span> <span class="pre">[(v,</span> <span class="pre">k)</span> <span class="pre">for</span> <span class="pre">(k,</span> <span class="pre">v)</span> <span class="pre">in</span> <span class="pre">d.items()]</span></tt>.</p> <p>Iterating views while adding or deleting entries in the dictionary may raise a <a class="reference internal" href="exceptions.html#exceptions.RuntimeError" title="exceptions.RuntimeError"><tt class="xref py py-exc docutils literal"><span class="pre">RuntimeError</span></tt></a> or fail to iterate over all entries.</p> </dd></dl> <dl class="describe"> <dt> <tt class="descname">x in dictview</tt></dt> <dd><p>Return <tt class="docutils literal"><span class="pre">True</span></tt> if <em>x</em> is in the underlying dictionary’s keys, values or items (in the latter case, <em>x</em> should be a <tt class="docutils literal"><span class="pre">(key,</span> <span class="pre">value)</span></tt> tuple).</p> </dd></dl> <p>Keys views are set-like since their entries are unique and hashable. If all values are hashable, so that (key, value) pairs are unique and hashable, then the items view is also set-like. (Values views are not treated as set-like since the entries are generally not unique.) Then these set operations are available (“other” refers either to another view or a set):</p> <dl class="describe"> <dt> <tt class="descname">dictview & other</tt></dt> <dd><p>Return the intersection of the dictview and the other object as a new set.</p> </dd></dl> <dl class="describe"> <dt> <tt class="descname">dictview | other</tt></dt> <dd><p>Return the union of the dictview and the other object as a new set.</p> </dd></dl> <dl class="describe"> <dt> <tt class="descname">dictview - other</tt></dt> <dd><p>Return the difference between the dictview and the other object (all elements in <em>dictview</em> that aren’t in <em>other</em>) as a new set.</p> </dd></dl> <dl class="describe"> <dt> <tt class="descname">dictview ^ other</tt></dt> <dd><p>Return the symmetric difference (all elements either in <em>dictview</em> or <em>other</em>, but not in both) of the dictview and the other object as a new set.</p> </dd></dl> <p>An example of dictionary view usage:</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">dishes</span> <span class="o">=</span> <span class="p">{</span><span class="s">'eggs'</span><span class="p">:</span> <span class="mi">2</span><span class="p">,</span> <span class="s">'sausage'</span><span class="p">:</span> <span class="mi">1</span><span class="p">,</span> <span class="s">'bacon'</span><span class="p">:</span> <span class="mi">1</span><span class="p">,</span> <span class="s">'spam'</span><span class="p">:</span> <span class="mi">500</span><span class="p">}</span> <span class="gp">>>> </span><span class="n">keys</span> <span class="o">=</span> <span class="n">dishes</span><span class="o">.</span><span class="n">viewkeys</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">values</span> <span class="o">=</span> <span class="n">dishes</span><span class="o">.</span><span class="n">viewvalues</span><span class="p">()</span> <span class="gp">>>> </span><span class="c"># iteration</span> <span class="gp">>>> </span><span class="n">n</span> <span class="o">=</span> <span class="mi">0</span> <span class="gp">>>> </span><span class="k">for</span> <span class="n">val</span> <span class="ow">in</span> <span class="n">values</span><span class="p">:</span> <span class="gp">... </span> <span class="n">n</span> <span class="o">+=</span> <span class="n">val</span> <span class="gp">>>> </span><span class="k">print</span><span class="p">(</span><span class="n">n</span><span class="p">)</span> <span class="go">504</span> <span class="gp">>>> </span><span class="c"># keys and values are iterated over in the same order</span> <span class="gp">>>> </span><span class="nb">list</span><span class="p">(</span><span class="n">keys</span><span class="p">)</span> <span class="go">['eggs', 'bacon', 'sausage', 'spam']</span> <span class="gp">>>> </span><span class="nb">list</span><span class="p">(</span><span class="n">values</span><span class="p">)</span> <span class="go">[2, 1, 1, 500]</span> <span class="gp">>>> </span><span class="c"># view objects are dynamic and reflect dict changes</span> <span class="gp">>>> </span><span class="k">del</span> <span class="n">dishes</span><span class="p">[</span><span class="s">'eggs'</span><span class="p">]</span> <span class="gp">>>> </span><span class="k">del</span> <span class="n">dishes</span><span class="p">[</span><span class="s">'sausage'</span><span class="p">]</span> <span class="gp">>>> </span><span class="nb">list</span><span class="p">(</span><span class="n">keys</span><span class="p">)</span> <span class="go">['spam', 'bacon']</span> <span class="gp">>>> </span><span class="c"># set operations</span> <span class="gp">>>> </span><span class="n">keys</span> <span class="o">&</span> <span class="p">{</span><span class="s">'eggs'</span><span class="p">,</span> <span class="s">'bacon'</span><span class="p">,</span> <span class="s">'salad'</span><span class="p">}</span> <span class="go">{'bacon'}</span> </pre></div> </div> </div> </div> <div class="section" id="file-objects"> <span id="bltin-file-objects"></span><h2>5.9. File Objects<a class="headerlink" href="#file-objects" title="Permalink to this headline">¶</a></h2> <p id="index-33">File objects are implemented using C’s <tt class="docutils literal"><span class="pre">stdio</span></tt> package and can be created with the built-in <a class="reference internal" href="functions.html#open" title="open"><tt class="xref py py-func docutils literal"><span class="pre">open()</span></tt></a> function. File objects are also returned by some other built-in functions and methods, such as <a class="reference internal" href="os.html#os.popen" title="os.popen"><tt class="xref py py-func docutils literal"><span class="pre">os.popen()</span></tt></a> and <a class="reference internal" href="os.html#os.fdopen" title="os.fdopen"><tt class="xref py py-func docutils literal"><span class="pre">os.fdopen()</span></tt></a> and the <tt class="xref py py-meth docutils literal"><span class="pre">makefile()</span></tt> method of socket objects. Temporary files can be created using the <a class="reference internal" href="tempfile.html#module-tempfile" title="tempfile: Generate temporary files and directories."><tt class="xref py py-mod docutils literal"><span class="pre">tempfile</span></tt></a> module, and high-level file operations such as copying, moving, and deleting files and directories can be achieved with the <a class="reference internal" href="shutil.html#module-shutil" title="shutil: High-level file operations, including copying."><tt class="xref py py-mod docutils literal"><span class="pre">shutil</span></tt></a> module.</p> <p>When a file operation fails for an I/O-related reason, the exception <a class="reference internal" href="exceptions.html#exceptions.IOError" title="exceptions.IOError"><tt class="xref py py-exc docutils literal"><span class="pre">IOError</span></tt></a> is raised. This includes situations where the operation is not defined for some reason, like <tt class="xref py py-meth docutils literal"><span class="pre">seek()</span></tt> on a tty device or writing a file opened for reading.</p> <p>Files have the following methods:</p> <dl class="method"> <dt id="file.close"> <tt class="descclassname">file.</tt><tt class="descname">close</tt><big>(</big><big>)</big><a class="headerlink" href="#file.close" title="Permalink to this definition">¶</a></dt> <dd><p>Close the file. A closed file cannot be read or written any more. Any operation which requires that the file be open will raise a <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><tt class="xref py py-exc docutils literal"><span class="pre">ValueError</span></tt></a> after the file has been closed. Calling <a class="reference internal" href="#file.close" title="file.close"><tt class="xref py py-meth docutils literal"><span class="pre">close()</span></tt></a> more than once is allowed.</p> <p>As of Python 2.5, you can avoid having to call this method explicitly if you use the <a class="reference internal" href="../reference/compound_stmts.html#with"><tt class="xref std std-keyword docutils literal"><span class="pre">with</span></tt></a> statement. For example, the following code will automatically close <em>f</em> when the <a class="reference internal" href="../reference/compound_stmts.html#with"><tt class="xref std std-keyword docutils literal"><span class="pre">with</span></tt></a> block is exited:</p> <div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">__future__</span> <span class="kn">import</span> <span class="n">with_statement</span> <span class="c"># This isn't required in Python 2.6</span> <span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s">"hello.txt"</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span> <span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="n">f</span><span class="p">:</span> <span class="k">print</span> <span class="n">line</span><span class="p">,</span> </pre></div> </div> <p>In older versions of Python, you would have needed to do this to get the same effect:</p> <div class="highlight-python"><div class="highlight"><pre><span class="n">f</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="s">"hello.txt"</span><span class="p">)</span> <span class="k">try</span><span class="p">:</span> <span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="n">f</span><span class="p">:</span> <span class="k">print</span> <span class="n">line</span><span class="p">,</span> <span class="k">finally</span><span class="p">:</span> <span class="n">f</span><span class="o">.</span><span class="n">close</span><span class="p">()</span> </pre></div> </div> <div class="admonition note"> <p class="first admonition-title">Note</p> <p class="last">Not all “file-like” types in Python support use as a context manager for the <a class="reference internal" href="../reference/compound_stmts.html#with"><tt class="xref std std-keyword docutils literal"><span class="pre">with</span></tt></a> statement. If your code is intended to work with any file-like object, you can use the function <a class="reference internal" href="contextlib.html#contextlib.closing" title="contextlib.closing"><tt class="xref py py-func docutils literal"><span class="pre">contextlib.closing()</span></tt></a> instead of using the object directly.</p> </div> </dd></dl> <dl class="method"> <dt id="file.flush"> <tt class="descclassname">file.</tt><tt class="descname">flush</tt><big>(</big><big>)</big><a class="headerlink" href="#file.flush" title="Permalink to this definition">¶</a></dt> <dd><p>Flush the internal buffer, like <tt class="docutils literal"><span class="pre">stdio</span></tt>‘s <tt class="xref c c-func docutils literal"><span class="pre">fflush()</span></tt>. This may be a no-op on some file-like objects.</p> <div class="admonition note"> <p class="first admonition-title">Note</p> <p class="last"><a class="reference internal" href="#file.flush" title="file.flush"><tt class="xref py py-meth docutils literal"><span class="pre">flush()</span></tt></a> does not necessarily write the file’s data to disk. Use <a class="reference internal" href="#file.flush" title="file.flush"><tt class="xref py py-meth docutils literal"><span class="pre">flush()</span></tt></a> followed by <a class="reference internal" href="os.html#os.fsync" title="os.fsync"><tt class="xref py py-func docutils literal"><span class="pre">os.fsync()</span></tt></a> to ensure this behavior.</p> </div> </dd></dl> <dl class="method"> <dt id="file.fileno"> <tt class="descclassname">file.</tt><tt class="descname">fileno</tt><big>(</big><big>)</big><a class="headerlink" href="#file.fileno" title="Permalink to this definition">¶</a></dt> <dd><p id="index-34">Return the integer “file descriptor” that is used by the underlying implementation to request I/O operations from the operating system. This can be useful for other, lower level interfaces that use file descriptors, such as the <a class="reference internal" href="fcntl.html#module-fcntl" title="fcntl: The fcntl() and ioctl() system calls. (Unix)"><tt class="xref py py-mod docutils literal"><span class="pre">fcntl</span></tt></a> module or <a class="reference internal" href="os.html#os.read" title="os.read"><tt class="xref py py-func docutils literal"><span class="pre">os.read()</span></tt></a> and friends.</p> <div class="admonition note"> <p class="first admonition-title">Note</p> <p class="last">File-like objects which do not have a real file descriptor should <em>not</em> provide this method!</p> </div> </dd></dl> <dl class="method"> <dt id="file.isatty"> <tt class="descclassname">file.</tt><tt class="descname">isatty</tt><big>(</big><big>)</big><a class="headerlink" href="#file.isatty" title="Permalink to this definition">¶</a></dt> <dd><p>Return <tt class="docutils literal"><span class="pre">True</span></tt> if the file is connected to a tty(-like) device, else <tt class="docutils literal"><span class="pre">False</span></tt>.</p> <div class="admonition note"> <p class="first admonition-title">Note</p> <p class="last">If a file-like object is not associated with a real file, this method should <em>not</em> be implemented.</p> </div> </dd></dl> <dl class="method"> <dt id="file.next"> <tt class="descclassname">file.</tt><tt class="descname">next</tt><big>(</big><big>)</big><a class="headerlink" href="#file.next" title="Permalink to this definition">¶</a></dt> <dd><p>A file object is its own iterator, for example <tt class="docutils literal"><span class="pre">iter(f)</span></tt> returns <em>f</em> (unless <em>f</em> is closed). When a file is used as an iterator, typically in a <a class="reference internal" href="../reference/compound_stmts.html#for"><tt class="xref std std-keyword docutils literal"><span class="pre">for</span></tt></a> loop (for example, <tt class="docutils literal"><span class="pre">for</span> <span class="pre">line</span> <span class="pre">in</span> <span class="pre">f:</span> <span class="pre">print</span> <span class="pre">line.strip()</span></tt>), the <a class="reference internal" href="#file.next" title="file.next"><tt class="xref py py-meth docutils literal"><span class="pre">next()</span></tt></a> method is called repeatedly. This method returns the next input line, or raises <a class="reference internal" href="exceptions.html#exceptions.StopIteration" title="exceptions.StopIteration"><tt class="xref py py-exc docutils literal"><span class="pre">StopIteration</span></tt></a> when EOF is hit when the file is open for reading (behavior is undefined when the file is open for writing). In order to make a <a class="reference internal" href="../reference/compound_stmts.html#for"><tt class="xref std std-keyword docutils literal"><span class="pre">for</span></tt></a> loop the most efficient way of looping over the lines of a file (a very common operation), the <a class="reference internal" href="#file.next" title="file.next"><tt class="xref py py-meth docutils literal"><span class="pre">next()</span></tt></a> method uses a hidden read-ahead buffer. As a consequence of using a read-ahead buffer, combining <a class="reference internal" href="#file.next" title="file.next"><tt class="xref py py-meth docutils literal"><span class="pre">next()</span></tt></a> with other file methods (like <a class="reference internal" href="#file.readline" title="file.readline"><tt class="xref py py-meth docutils literal"><span class="pre">readline()</span></tt></a>) does not work right. However, using <a class="reference internal" href="#file.seek" title="file.seek"><tt class="xref py py-meth docutils literal"><span class="pre">seek()</span></tt></a> to reposition the file to an absolute position will flush the read-ahead buffer.</p> <p class="versionadded"> <span class="versionmodified">New in version 2.3.</span></p> </dd></dl> <dl class="method"> <dt id="file.read"> <tt class="descclassname">file.</tt><tt class="descname">read</tt><big>(</big><span class="optional">[</span><em>size</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#file.read" title="Permalink to this definition">¶</a></dt> <dd><p>Read at most <em>size</em> bytes from the file (less if the read hits EOF before obtaining <em>size</em> bytes). If the <em>size</em> argument is negative or omitted, read all data until EOF is reached. The bytes are returned as a string object. An empty string is returned when EOF is encountered immediately. (For certain files, like ttys, it makes sense to continue reading after an EOF is hit.) Note that this method may call the underlying C function <tt class="xref c c-func docutils literal"><span class="pre">fread()</span></tt> more than once in an effort to acquire as close to <em>size</em> bytes as possible. Also note that when in non-blocking mode, less data than was requested may be returned, even if no <em>size</em> parameter was given.</p> <div class="admonition note"> <p class="first admonition-title">Note</p> <p class="last">This function is simply a wrapper for the underlying <tt class="xref c c-func docutils literal"><span class="pre">fread()</span></tt> C function, and will behave the same in corner cases, such as whether the EOF value is cached.</p> </div> </dd></dl> <dl class="method"> <dt id="file.readline"> <tt class="descclassname">file.</tt><tt class="descname">readline</tt><big>(</big><span class="optional">[</span><em>size</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#file.readline" title="Permalink to this definition">¶</a></dt> <dd><p>Read one entire line from the file. A trailing newline character is kept in the string (but may be absent when a file ends with an incomplete line). <a class="footnote-reference" href="#id17" id="id11">[6]</a> If the <em>size</em> argument is present and non-negative, it is a maximum byte count (including the trailing newline) and an incomplete line may be returned. When <em>size</em> is not 0, an empty string is returned <em>only</em> when EOF is encountered immediately.</p> <div class="admonition note"> <p class="first admonition-title">Note</p> <p class="last">Unlike <tt class="docutils literal"><span class="pre">stdio</span></tt>‘s <tt class="xref c c-func docutils literal"><span class="pre">fgets()</span></tt>, the returned string contains null characters (<tt class="docutils literal"><span class="pre">'\0'</span></tt>) if they occurred in the input.</p> </div> </dd></dl> <dl class="method"> <dt id="file.readlines"> <tt class="descclassname">file.</tt><tt class="descname">readlines</tt><big>(</big><span class="optional">[</span><em>sizehint</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#file.readlines" title="Permalink to this definition">¶</a></dt> <dd><p>Read until EOF using <a class="reference internal" href="#file.readline" title="file.readline"><tt class="xref py py-meth docutils literal"><span class="pre">readline()</span></tt></a> and return a list containing the lines thus read. If the optional <em>sizehint</em> argument is present, instead of reading up to EOF, whole lines totalling approximately <em>sizehint</em> bytes (possibly after rounding up to an internal buffer size) are read. Objects implementing a file-like interface may choose to ignore <em>sizehint</em> if it cannot be implemented, or cannot be implemented efficiently.</p> </dd></dl> <dl class="method"> <dt id="file.xreadlines"> <tt class="descclassname">file.</tt><tt class="descname">xreadlines</tt><big>(</big><big>)</big><a class="headerlink" href="#file.xreadlines" title="Permalink to this definition">¶</a></dt> <dd><p>This method returns the same thing as <tt class="docutils literal"><span class="pre">iter(f)</span></tt>.</p> <p class="versionadded"> <span class="versionmodified">New in version 2.1.</span></p> <p class="deprecated"> <span class="versionmodified">Deprecated since version 2.3: </span>Use <tt class="docutils literal"><span class="pre">for</span> <span class="pre">line</span> <span class="pre">in</span> <span class="pre">file</span></tt> instead.</p> </dd></dl> <dl class="method"> <dt id="file.seek"> <tt class="descclassname">file.</tt><tt class="descname">seek</tt><big>(</big><em>offset</em><span class="optional">[</span>, <em>whence</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#file.seek" title="Permalink to this definition">¶</a></dt> <dd><p>Set the file’s current position, like <tt class="docutils literal"><span class="pre">stdio</span></tt>‘s <tt class="xref c c-func docutils literal"><span class="pre">fseek()</span></tt>. The <em>whence</em> argument is optional and defaults to <tt class="docutils literal"><span class="pre">os.SEEK_SET</span></tt> or <tt class="docutils literal"><span class="pre">0</span></tt> (absolute file positioning); other values are <tt class="docutils literal"><span class="pre">os.SEEK_CUR</span></tt> or <tt class="docutils literal"><span class="pre">1</span></tt> (seek relative to the current position) and <tt class="docutils literal"><span class="pre">os.SEEK_END</span></tt> or <tt class="docutils literal"><span class="pre">2</span></tt> (seek relative to the file’s end). There is no return value.</p> <p>For example, <tt class="docutils literal"><span class="pre">f.seek(2,</span> <span class="pre">os.SEEK_CUR)</span></tt> advances the position by two and <tt class="docutils literal"><span class="pre">f.seek(-3,</span> <span class="pre">os.SEEK_END)</span></tt> sets the position to the third to last.</p> <p>Note that if the file is opened for appending (mode <tt class="docutils literal"><span class="pre">'a'</span></tt> or <tt class="docutils literal"><span class="pre">'a+'</span></tt>), any <a class="reference internal" href="#file.seek" title="file.seek"><tt class="xref py py-meth docutils literal"><span class="pre">seek()</span></tt></a> operations will be undone at the next write. If the file is only opened for writing in append mode (mode <tt class="docutils literal"><span class="pre">'a'</span></tt>), this method is essentially a no-op, but it remains useful for files opened in append mode with reading enabled (mode <tt class="docutils literal"><span class="pre">'a+'</span></tt>). If the file is opened in text mode (without <tt class="docutils literal"><span class="pre">'b'</span></tt>), only offsets returned by <a class="reference internal" href="#file.tell" title="file.tell"><tt class="xref py py-meth docutils literal"><span class="pre">tell()</span></tt></a> are legal. Use of other offsets causes undefined behavior.</p> <p>Note that not all file objects are seekable.</p> <p class="versionchanged"> <span class="versionmodified">Changed in version 2.6: </span>Passing float values as offset has been deprecated.</p> </dd></dl> <dl class="method"> <dt id="file.tell"> <tt class="descclassname">file.</tt><tt class="descname">tell</tt><big>(</big><big>)</big><a class="headerlink" href="#file.tell" title="Permalink to this definition">¶</a></dt> <dd><p>Return the file’s current position, like <tt class="docutils literal"><span class="pre">stdio</span></tt>‘s <tt class="xref c c-func docutils literal"><span class="pre">ftell()</span></tt>.</p> <div class="admonition note"> <p class="first admonition-title">Note</p> <p class="last">On Windows, <a class="reference internal" href="#file.tell" title="file.tell"><tt class="xref py py-meth docutils literal"><span class="pre">tell()</span></tt></a> can return illegal values (after an <tt class="xref c c-func docutils literal"><span class="pre">fgets()</span></tt>) when reading files with Unix-style line-endings. Use binary mode (<tt class="docutils literal"><span class="pre">'rb'</span></tt>) to circumvent this problem.</p> </div> </dd></dl> <dl class="method"> <dt id="file.truncate"> <tt class="descclassname">file.</tt><tt class="descname">truncate</tt><big>(</big><span class="optional">[</span><em>size</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#file.truncate" title="Permalink to this definition">¶</a></dt> <dd><p>Truncate the file’s size. If the optional <em>size</em> argument is present, the file is truncated to (at most) that size. The size defaults to the current position. The current file position is not changed. Note that if a specified size exceeds the file’s current size, the result is platform-dependent: possibilities include that the file may remain unchanged, increase to the specified size as if zero-filled, or increase to the specified size with undefined new content. Availability: Windows, many Unix variants.</p> </dd></dl> <dl class="method"> <dt id="file.write"> <tt class="descclassname">file.</tt><tt class="descname">write</tt><big>(</big><em>str</em><big>)</big><a class="headerlink" href="#file.write" title="Permalink to this definition">¶</a></dt> <dd><p>Write a string to the file. There is no return value. Due to buffering, the string may not actually show up in the file until the <a class="reference internal" href="#file.flush" title="file.flush"><tt class="xref py py-meth docutils literal"><span class="pre">flush()</span></tt></a> or <a class="reference internal" href="#file.close" title="file.close"><tt class="xref py py-meth docutils literal"><span class="pre">close()</span></tt></a> method is called.</p> </dd></dl> <dl class="method"> <dt id="file.writelines"> <tt class="descclassname">file.</tt><tt class="descname">writelines</tt><big>(</big><em>sequence</em><big>)</big><a class="headerlink" href="#file.writelines" title="Permalink to this definition">¶</a></dt> <dd><p>Write a sequence of strings to the file. The sequence can be any iterable object producing strings, typically a list of strings. There is no return value. (The name is intended to match <a class="reference internal" href="#file.readlines" title="file.readlines"><tt class="xref py py-meth docutils literal"><span class="pre">readlines()</span></tt></a>; <a class="reference internal" href="#file.writelines" title="file.writelines"><tt class="xref py py-meth docutils literal"><span class="pre">writelines()</span></tt></a> does not add line separators.)</p> </dd></dl> <p>Files support the iterator protocol. Each iteration returns the same result as <a class="reference internal" href="#file.readline" title="file.readline"><tt class="xref py py-meth docutils literal"><span class="pre">readline()</span></tt></a>, and iteration ends when the <a class="reference internal" href="#file.readline" title="file.readline"><tt class="xref py py-meth docutils literal"><span class="pre">readline()</span></tt></a> method returns an empty string.</p> <p>File objects also offer a number of other interesting attributes. These are not required for file-like objects, but should be implemented if they make sense for the particular object.</p> <dl class="attribute"> <dt id="file.closed"> <tt class="descclassname">file.</tt><tt class="descname">closed</tt><a class="headerlink" href="#file.closed" title="Permalink to this definition">¶</a></dt> <dd><p>bool indicating the current state of the file object. This is a read-only attribute; the <a class="reference internal" href="#file.close" title="file.close"><tt class="xref py py-meth docutils literal"><span class="pre">close()</span></tt></a> method changes the value. It may not be available on all file-like objects.</p> </dd></dl> <dl class="attribute"> <dt id="file.encoding"> <tt class="descclassname">file.</tt><tt class="descname">encoding</tt><a class="headerlink" href="#file.encoding" title="Permalink to this definition">¶</a></dt> <dd><p>The encoding that this file uses. When Unicode strings are written to a file, they will be converted to byte strings using this encoding. In addition, when the file is connected to a terminal, the attribute gives the encoding that the terminal is likely to use (that information might be incorrect if the user has misconfigured the terminal). The attribute is read-only and may not be present on all file-like objects. It may also be <tt class="docutils literal"><span class="pre">None</span></tt>, in which case the file uses the system default encoding for converting Unicode strings.</p> <p class="versionadded"> <span class="versionmodified">New in version 2.3.</span></p> </dd></dl> <dl class="attribute"> <dt id="file.errors"> <tt class="descclassname">file.</tt><tt class="descname">errors</tt><a class="headerlink" href="#file.errors" title="Permalink to this definition">¶</a></dt> <dd><p>The Unicode error handler used along with the encoding.</p> <p class="versionadded"> <span class="versionmodified">New in version 2.6.</span></p> </dd></dl> <dl class="attribute"> <dt id="file.mode"> <tt class="descclassname">file.</tt><tt class="descname">mode</tt><a class="headerlink" href="#file.mode" title="Permalink to this definition">¶</a></dt> <dd><p>The I/O mode for the file. If the file was created using the <a class="reference internal" href="functions.html#open" title="open"><tt class="xref py py-func docutils literal"><span class="pre">open()</span></tt></a> built-in function, this will be the value of the <em>mode</em> parameter. This is a read-only attribute and may not be present on all file-like objects.</p> </dd></dl> <dl class="attribute"> <dt id="file.name"> <tt class="descclassname">file.</tt><tt class="descname">name</tt><a class="headerlink" href="#file.name" title="Permalink to this definition">¶</a></dt> <dd><p>If the file object was created using <a class="reference internal" href="functions.html#open" title="open"><tt class="xref py py-func docutils literal"><span class="pre">open()</span></tt></a>, the name of the file. Otherwise, some string that indicates the source of the file object, of the form <tt class="docutils literal"><span class="pre"><...></span></tt>. This is a read-only attribute and may not be present on all file-like objects.</p> <span class="target" id="index-35"></span></dd></dl> <dl class="attribute"> <dt id="file.newlines"> <tt class="descclassname">file.</tt><tt class="descname">newlines</tt><a class="headerlink" href="#file.newlines" title="Permalink to this definition">¶</a></dt> <dd><p>If Python was built with <a class="reference internal" href="../glossary.html#term-universal-newlines"><em class="xref std std-term">universal newlines</em></a> enabled (the default) this read-only attribute exists, and for files opened in universal newline read mode it keeps track of the types of newlines encountered while reading the file. The values it can take are <tt class="docutils literal"><span class="pre">'\r'</span></tt>, <tt class="docutils literal"><span class="pre">'\n'</span></tt>, <tt class="docutils literal"><span class="pre">'\r\n'</span></tt>, <tt class="docutils literal"><span class="pre">None</span></tt> (unknown, no newlines read yet) or a tuple containing all the newline types seen, to indicate that multiple newline conventions were encountered. For files not opened in universal newlines read mode the value of this attribute will be <tt class="docutils literal"><span class="pre">None</span></tt>.</p> </dd></dl> <dl class="attribute"> <dt id="file.softspace"> <tt class="descclassname">file.</tt><tt class="descname">softspace</tt><a class="headerlink" href="#file.softspace" title="Permalink to this definition">¶</a></dt> <dd><p>Boolean that indicates whether a space character needs to be printed before another value when using the <a class="reference internal" href="../reference/simple_stmts.html#print"><tt class="xref std std-keyword docutils literal"><span class="pre">print</span></tt></a> statement. Classes that are trying to simulate a file object should also have a writable <a class="reference internal" href="#file.softspace" title="file.softspace"><tt class="xref py py-attr docutils literal"><span class="pre">softspace</span></tt></a> attribute, which should be initialized to zero. This will be automatic for most classes implemented in Python (care may be needed for objects that override attribute access); types implemented in C will have to provide a writable <a class="reference internal" href="#file.softspace" title="file.softspace"><tt class="xref py py-attr docutils literal"><span class="pre">softspace</span></tt></a> attribute.</p> <div class="admonition note"> <p class="first admonition-title">Note</p> <p class="last">This attribute is not used to control the <a class="reference internal" href="../reference/simple_stmts.html#print"><tt class="xref std std-keyword docutils literal"><span class="pre">print</span></tt></a> statement, but to allow the implementation of <a class="reference internal" href="../reference/simple_stmts.html#print"><tt class="xref std std-keyword docutils literal"><span class="pre">print</span></tt></a> to keep track of its internal state.</p> </div> </dd></dl> </div> <div class="section" id="memoryview-type"> <span id="typememoryview"></span><h2>5.10. memoryview type<a class="headerlink" href="#memoryview-type" title="Permalink to this headline">¶</a></h2> <p class="versionadded"> <span class="versionmodified">New in version 2.7.</span></p> <p><a class="reference internal" href="#memoryview" title="memoryview"><tt class="xref py py-class docutils literal"><span class="pre">memoryview</span></tt></a> objects allow Python code to access the internal data of an object that supports the buffer protocol without copying. Memory is generally interpreted as simple bytes.</p> <dl class="class"> <dt id="memoryview"> <em class="property">class </em><tt class="descname">memoryview</tt><big>(</big><em>obj</em><big>)</big><a class="headerlink" href="#memoryview" title="Permalink to this definition">¶</a></dt> <dd><p>Create a <a class="reference internal" href="#memoryview" title="memoryview"><tt class="xref py py-class docutils literal"><span class="pre">memoryview</span></tt></a> that references <em>obj</em>. <em>obj</em> must support the buffer protocol. Built-in objects that support the buffer protocol include <a class="reference internal" href="functions.html#str" title="str"><tt class="xref py py-class docutils literal"><span class="pre">str</span></tt></a> and <a class="reference internal" href="functions.html#bytearray" title="bytearray"><tt class="xref py py-class docutils literal"><span class="pre">bytearray</span></tt></a> (but not <a class="reference internal" href="functions.html#unicode" title="unicode"><tt class="xref py py-class docutils literal"><span class="pre">unicode</span></tt></a>).</p> <p>A <a class="reference internal" href="#memoryview" title="memoryview"><tt class="xref py py-class docutils literal"><span class="pre">memoryview</span></tt></a> has the notion of an <em>element</em>, which is the atomic memory unit handled by the originating object <em>obj</em>. For many simple types such as <a class="reference internal" href="functions.html#str" title="str"><tt class="xref py py-class docutils literal"><span class="pre">str</span></tt></a> and <a class="reference internal" href="functions.html#bytearray" title="bytearray"><tt class="xref py py-class docutils literal"><span class="pre">bytearray</span></tt></a>, an element is a single byte, but other third-party types may expose larger elements.</p> <p><tt class="docutils literal"><span class="pre">len(view)</span></tt> returns the total number of elements in the memoryview, <em>view</em>. The <a class="reference internal" href="#memoryview.itemsize" title="memoryview.itemsize"><tt class="xref py py-class docutils literal"><span class="pre">itemsize</span></tt></a> attribute will give you the number of bytes in a single element.</p> <p>A <a class="reference internal" href="#memoryview" title="memoryview"><tt class="xref py py-class docutils literal"><span class="pre">memoryview</span></tt></a> supports slicing to expose its data. Taking a single index will return a single element as a <a class="reference internal" href="functions.html#str" title="str"><tt class="xref py py-class docutils literal"><span class="pre">str</span></tt></a> object. Full slicing will result in a subview:</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">v</span> <span class="o">=</span> <span class="n">memoryview</span><span class="p">(</span><span class="s">'abcefg'</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">v</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span> <span class="go">'b'</span> <span class="gp">>>> </span><span class="n">v</span><span class="p">[</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span> <span class="go">'g'</span> <span class="gp">>>> </span><span class="n">v</span><span class="p">[</span><span class="mi">1</span><span class="p">:</span><span class="mi">4</span><span class="p">]</span> <span class="go"><memory at 0x77ab28></span> <span class="gp">>>> </span><span class="n">v</span><span class="p">[</span><span class="mi">1</span><span class="p">:</span><span class="mi">4</span><span class="p">]</span><span class="o">.</span><span class="n">tobytes</span><span class="p">()</span> <span class="go">'bce'</span> </pre></div> </div> <p>If the object the memoryview is over supports changing its data, the memoryview supports slice assignment:</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">data</span> <span class="o">=</span> <span class="nb">bytearray</span><span class="p">(</span><span class="s">'abcefg'</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">v</span> <span class="o">=</span> <span class="n">memoryview</span><span class="p">(</span><span class="n">data</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">v</span><span class="o">.</span><span class="n">readonly</span> <span class="go">False</span> <span class="gp">>>> </span><span class="n">v</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">=</span> <span class="s">'z'</span> <span class="gp">>>> </span><span class="n">data</span> <span class="go">bytearray(b'zbcefg')</span> <span class="gp">>>> </span><span class="n">v</span><span class="p">[</span><span class="mi">1</span><span class="p">:</span><span class="mi">4</span><span class="p">]</span> <span class="o">=</span> <span class="s">'123'</span> <span class="gp">>>> </span><span class="n">data</span> <span class="go">bytearray(b'z123fg')</span> <span class="gp">>>> </span><span class="n">v</span><span class="p">[</span><span class="mi">2</span><span class="p">]</span> <span class="o">=</span> <span class="s">'spam'</span> <span class="gt">Traceback (most recent call last):</span> File <span class="nb">"<stdin>"</span>, line <span class="m">1</span>, in <span class="n"><module></span> <span class="gr">ValueError</span>: <span class="n">cannot modify size of memoryview object</span> </pre></div> </div> <p>Notice how the size of the memoryview object cannot be changed.</p> <p><a class="reference internal" href="#memoryview" title="memoryview"><tt class="xref py py-class docutils literal"><span class="pre">memoryview</span></tt></a> has two methods:</p> <dl class="method"> <dt id="memoryview.tobytes"> <tt class="descname">tobytes</tt><big>(</big><big>)</big><a class="headerlink" href="#memoryview.tobytes" title="Permalink to this definition">¶</a></dt> <dd><p>Return the data in the buffer as a bytestring (an object of class <a class="reference internal" href="functions.html#str" title="str"><tt class="xref py py-class docutils literal"><span class="pre">str</span></tt></a>).</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">m</span> <span class="o">=</span> <span class="n">memoryview</span><span class="p">(</span><span class="s">"abc"</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">m</span><span class="o">.</span><span class="n">tobytes</span><span class="p">()</span> <span class="go">'abc'</span> </pre></div> </div> </dd></dl> <dl class="method"> <dt id="memoryview.tolist"> <tt class="descname">tolist</tt><big>(</big><big>)</big><a class="headerlink" href="#memoryview.tolist" title="Permalink to this definition">¶</a></dt> <dd><p>Return the data in the buffer as a list of integers.</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">memoryview</span><span class="p">(</span><span class="s">"abc"</span><span class="p">)</span><span class="o">.</span><span class="n">tolist</span><span class="p">()</span> <span class="go">[97, 98, 99]</span> </pre></div> </div> </dd></dl> <p>There are also several readonly attributes available:</p> <dl class="attribute"> <dt id="memoryview.format"> <tt class="descname">format</tt><a class="headerlink" href="#memoryview.format" title="Permalink to this definition">¶</a></dt> <dd><p>A string containing the format (in <a class="reference internal" href="struct.html#module-struct" title="struct: Interpret strings as packed binary data."><tt class="xref py py-mod docutils literal"><span class="pre">struct</span></tt></a> module style) for each element in the view. This defaults to <tt class="docutils literal"><span class="pre">'B'</span></tt>, a simple bytestring.</p> </dd></dl> <dl class="attribute"> <dt id="memoryview.itemsize"> <tt class="descname">itemsize</tt><a class="headerlink" href="#memoryview.itemsize" title="Permalink to this definition">¶</a></dt> <dd><p>The size in bytes of each element of the memoryview.</p> </dd></dl> <dl class="attribute"> <dt id="memoryview.shape"> <tt class="descname">shape</tt><a class="headerlink" href="#memoryview.shape" title="Permalink to this definition">¶</a></dt> <dd><p>A tuple of integers the length of <a class="reference internal" href="#memoryview.ndim" title="memoryview.ndim"><tt class="xref py py-attr docutils literal"><span class="pre">ndim</span></tt></a> giving the shape of the memory as a N-dimensional array.</p> </dd></dl> <dl class="attribute"> <dt id="memoryview.ndim"> <tt class="descname">ndim</tt><a class="headerlink" href="#memoryview.ndim" title="Permalink to this definition">¶</a></dt> <dd><p>An integer indicating how many dimensions of a multi-dimensional array the memory represents.</p> </dd></dl> <dl class="attribute"> <dt id="memoryview.strides"> <tt class="descname">strides</tt><a class="headerlink" href="#memoryview.strides" title="Permalink to this definition">¶</a></dt> <dd><p>A tuple of integers the length of <a class="reference internal" href="#memoryview.ndim" title="memoryview.ndim"><tt class="xref py py-attr docutils literal"><span class="pre">ndim</span></tt></a> giving the size in bytes to access each element for each dimension of the array.</p> </dd></dl> <dl class="attribute"> <dt id="memoryview.readonly"> <tt class="descname">readonly</tt><a class="headerlink" href="#memoryview.readonly" title="Permalink to this definition">¶</a></dt> <dd><p>A bool indicating whether the memory is read only.</p> </dd></dl> </dd></dl> </div> <div class="section" id="context-manager-types"> <span id="typecontextmanager"></span><h2>5.11. Context Manager Types<a class="headerlink" href="#context-manager-types" title="Permalink to this headline">¶</a></h2> <p class="versionadded"> <span class="versionmodified">New in version 2.5.</span></p> <p id="index-36">Python’s <a class="reference internal" href="../reference/compound_stmts.html#with"><tt class="xref std std-keyword docutils literal"><span class="pre">with</span></tt></a> statement supports the concept of a runtime context defined by a context manager. This is implemented using two separate methods that allow user-defined classes to define a runtime context that is entered before the statement body is executed and exited when the statement ends.</p> <p>The <em class="dfn">context management protocol</em> consists of a pair of methods that need to be provided for a context manager object to define a runtime context:</p> <dl class="method"> <dt id="contextmanager.__enter__"> <tt class="descclassname">contextmanager.</tt><tt class="descname">__enter__</tt><big>(</big><big>)</big><a class="headerlink" href="#contextmanager.__enter__" title="Permalink to this definition">¶</a></dt> <dd><p>Enter the runtime context and return either this object or another object related to the runtime context. The value returned by this method is bound to the identifier in the <a class="reference internal" href="../reference/compound_stmts.html#as"><tt class="xref std std-keyword docutils literal"><span class="pre">as</span></tt></a> clause of <a class="reference internal" href="../reference/compound_stmts.html#with"><tt class="xref std std-keyword docutils literal"><span class="pre">with</span></tt></a> statements using this context manager.</p> <p>An example of a context manager that returns itself is a file object. File objects return themselves from __enter__() to allow <a class="reference internal" href="functions.html#open" title="open"><tt class="xref py py-func docutils literal"><span class="pre">open()</span></tt></a> to be used as the context expression in a <a class="reference internal" href="../reference/compound_stmts.html#with"><tt class="xref std std-keyword docutils literal"><span class="pre">with</span></tt></a> statement.</p> <p>An example of a context manager that returns a related object is the one returned by <a class="reference internal" href="decimal.html#decimal.localcontext" title="decimal.localcontext"><tt class="xref py py-func docutils literal"><span class="pre">decimal.localcontext()</span></tt></a>. These managers set the active decimal context to a copy of the original decimal context and then return the copy. This allows changes to be made to the current decimal context in the body of the <a class="reference internal" href="../reference/compound_stmts.html#with"><tt class="xref std std-keyword docutils literal"><span class="pre">with</span></tt></a> statement without affecting code outside the <a class="reference internal" href="../reference/compound_stmts.html#with"><tt class="xref std std-keyword docutils literal"><span class="pre">with</span></tt></a> statement.</p> </dd></dl> <dl class="method"> <dt id="contextmanager.__exit__"> <tt class="descclassname">contextmanager.</tt><tt class="descname">__exit__</tt><big>(</big><em>exc_type</em>, <em>exc_val</em>, <em>exc_tb</em><big>)</big><a class="headerlink" href="#contextmanager.__exit__" title="Permalink to this definition">¶</a></dt> <dd><p>Exit the runtime context and return a Boolean flag indicating if any exception that occurred should be suppressed. If an exception occurred while executing the body of the <a class="reference internal" href="../reference/compound_stmts.html#with"><tt class="xref std std-keyword docutils literal"><span class="pre">with</span></tt></a> statement, the arguments contain the exception type, value and traceback information. Otherwise, all three arguments are <tt class="docutils literal"><span class="pre">None</span></tt>.</p> <p>Returning a true value from this method will cause the <a class="reference internal" href="../reference/compound_stmts.html#with"><tt class="xref std std-keyword docutils literal"><span class="pre">with</span></tt></a> statement to suppress the exception and continue execution with the statement immediately following the <a class="reference internal" href="../reference/compound_stmts.html#with"><tt class="xref std std-keyword docutils literal"><span class="pre">with</span></tt></a> statement. Otherwise the exception continues propagating after this method has finished executing. Exceptions that occur during execution of this method will replace any exception that occurred in the body of the <a class="reference internal" href="../reference/compound_stmts.html#with"><tt class="xref std std-keyword docutils literal"><span class="pre">with</span></tt></a> statement.</p> <p>The exception passed in should never be reraised explicitly - instead, this method should return a false value to indicate that the method completed successfully and does not want to suppress the raised exception. This allows context management code (such as <tt class="docutils literal"><span class="pre">contextlib.nested</span></tt>) to easily detect whether or not an <a class="reference internal" href="#contextmanager.__exit__" title="contextmanager.__exit__"><tt class="xref py py-meth docutils literal"><span class="pre">__exit__()</span></tt></a> method has actually failed.</p> </dd></dl> <p>Python defines several context managers to support easy thread synchronisation, prompt closure of files or other objects, and simpler manipulation of the active decimal arithmetic context. The specific types are not treated specially beyond their implementation of the context management protocol. See the <a class="reference internal" href="contextlib.html#module-contextlib" title="contextlib: Utilities for with-statement contexts."><tt class="xref py py-mod docutils literal"><span class="pre">contextlib</span></tt></a> module for some examples.</p> <p>Python’s <a class="reference internal" href="../glossary.html#term-generator"><em class="xref std std-term">generator</em></a>s and the <tt class="docutils literal"><span class="pre">contextlib.contextmanager</span></tt> <a class="reference internal" href="../glossary.html#term-decorator"><em class="xref std std-term">decorator</em></a> provide a convenient way to implement these protocols. If a generator function is decorated with the <tt class="docutils literal"><span class="pre">contextlib.contextmanager</span></tt> decorator, it will return a context manager implementing the necessary <a class="reference internal" href="../reference/datamodel.html#object.__enter__" title="object.__enter__"><tt class="xref py py-meth docutils literal"><span class="pre">__enter__()</span></tt></a> and <a class="reference internal" href="../reference/datamodel.html#object.__exit__" title="object.__exit__"><tt class="xref py py-meth docutils literal"><span class="pre">__exit__()</span></tt></a> methods, rather than the iterator produced by an undecorated generator function.</p> <p>Note that there is no specific slot for any of these methods in the type structure for Python objects in the Python/C API. Extension types wanting to define these methods must provide them as a normal Python accessible method. Compared to the overhead of setting up the runtime context, the overhead of a single class dictionary lookup is negligible.</p> </div> <div class="section" id="other-built-in-types"> <span id="typesother"></span><h2>5.12. Other Built-in Types<a class="headerlink" href="#other-built-in-types" title="Permalink to this headline">¶</a></h2> <p>The interpreter supports several other kinds of objects. Most of these support only one or two operations.</p> <div class="section" id="modules"> <span id="typesmodules"></span><h3>5.12.1. Modules<a class="headerlink" href="#modules" title="Permalink to this headline">¶</a></h3> <p>The only special operation on a module is attribute access: <tt class="docutils literal"><span class="pre">m.name</span></tt>, where <em>m</em> is a module and <em>name</em> accesses a name defined in <em>m</em>‘s symbol table. Module attributes can be assigned to. (Note that the <a class="reference internal" href="../reference/simple_stmts.html#import"><tt class="xref std std-keyword docutils literal"><span class="pre">import</span></tt></a> statement is not, strictly speaking, an operation on a module object; <tt class="docutils literal"><span class="pre">import</span> <span class="pre">foo</span></tt> does not require a module object named <em>foo</em> to exist, rather it requires an (external) <em>definition</em> for a module named <em>foo</em> somewhere.)</p> <p>A special attribute of every module is <tt class="xref py py-attr docutils literal"><span class="pre">__dict__</span></tt>. This is the dictionary containing the module’s symbol table. Modifying this dictionary will actually change the module’s symbol table, but direct assignment to the <tt class="xref py py-attr docutils literal"><span class="pre">__dict__</span></tt> attribute is not possible (you can write <tt class="docutils literal"><span class="pre">m.__dict__['a']</span> <span class="pre">=</span> <span class="pre">1</span></tt>, which defines <tt class="docutils literal"><span class="pre">m.a</span></tt> to be <tt class="docutils literal"><span class="pre">1</span></tt>, but you can’t write <tt class="docutils literal"><span class="pre">m.__dict__</span> <span class="pre">=</span> <span class="pre">{}</span></tt>). Modifying <tt class="xref py py-attr docutils literal"><span class="pre">__dict__</span></tt> directly is not recommended.</p> <p>Modules built into the interpreter are written like this: <tt class="docutils literal"><span class="pre"><module</span> <span class="pre">'sys'</span> <span class="pre">(built-in)></span></tt>. If loaded from a file, they are written as <tt class="docutils literal"><span class="pre"><module</span> <span class="pre">'os'</span> <span class="pre">from</span> <span class="pre">'/usr/local/lib/pythonX.Y/os.pyc'></span></tt>.</p> </div> <div class="section" id="classes-and-class-instances"> <span id="typesobjects"></span><h3>5.12.2. Classes and Class Instances<a class="headerlink" href="#classes-and-class-instances" title="Permalink to this headline">¶</a></h3> <p>See <a class="reference internal" href="../reference/datamodel.html#objects"><em>Objects, values and types</em></a> and <a class="reference internal" href="../reference/compound_stmts.html#class"><em>Class definitions</em></a> for these.</p> </div> <div class="section" id="functions"> <span id="typesfunctions"></span><h3>5.12.3. Functions<a class="headerlink" href="#functions" title="Permalink to this headline">¶</a></h3> <p>Function objects are created by function definitions. The only operation on a function object is to call it: <tt class="docutils literal"><span class="pre">func(argument-list)</span></tt>.</p> <p>There are really two flavors of function objects: built-in functions and user-defined functions. Both support the same operation (to call the function), but the implementation is different, hence the different object types.</p> <p>See <a class="reference internal" href="../reference/compound_stmts.html#function"><em>Function definitions</em></a> for more information.</p> </div> <div class="section" id="methods"> <span id="typesmethods"></span><h3>5.12.4. Methods<a class="headerlink" href="#methods" title="Permalink to this headline">¶</a></h3> <p id="index-37">Methods are functions that are called using the attribute notation. There are two flavors: built-in methods (such as <tt class="xref py py-meth docutils literal"><span class="pre">append()</span></tt> on lists) and class instance methods. Built-in methods are described with the types that support them.</p> <p>The implementation adds two special read-only attributes to class instance methods: <tt class="docutils literal"><span class="pre">m.im_self</span></tt> is the object on which the method operates, and <tt class="docutils literal"><span class="pre">m.im_func</span></tt> is the function implementing the method. Calling <tt class="docutils literal"><span class="pre">m(arg-1,</span> <span class="pre">arg-2,</span> <span class="pre">...,</span> <span class="pre">arg-n)</span></tt> is completely equivalent to calling <tt class="docutils literal"><span class="pre">m.im_func(m.im_self,</span> <span class="pre">arg-1,</span> <span class="pre">arg-2,</span> <span class="pre">...,</span> <span class="pre">arg-n)</span></tt>.</p> <p>Class instance methods are either <em>bound</em> or <em>unbound</em>, referring to whether the method was accessed through an instance or a class, respectively. When a method is unbound, its <tt class="docutils literal"><span class="pre">im_self</span></tt> attribute will be <tt class="docutils literal"><span class="pre">None</span></tt> and if called, an explicit <tt class="docutils literal"><span class="pre">self</span></tt> object must be passed as the first argument. In this case, <tt class="docutils literal"><span class="pre">self</span></tt> must be an instance of the unbound method’s class (or a subclass of that class), otherwise a <a class="reference internal" href="exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><tt class="xref py py-exc docutils literal"><span class="pre">TypeError</span></tt></a> is raised.</p> <p>Like function objects, methods objects support getting arbitrary attributes. However, since method attributes are actually stored on the underlying function object (<tt class="docutils literal"><span class="pre">meth.im_func</span></tt>), setting method attributes on either bound or unbound methods is disallowed. Attempting to set an attribute on a method results in an <a class="reference internal" href="exceptions.html#exceptions.AttributeError" title="exceptions.AttributeError"><tt class="xref py py-exc docutils literal"><span class="pre">AttributeError</span></tt></a> being raised. In order to set a method attribute, you need to explicitly set it on the underlying function object:</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="k">class</span> <span class="nc">C</span><span class="p">:</span> <span class="gp">... </span> <span class="k">def</span> <span class="nf">method</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="gp">... </span> <span class="k">pass</span> <span class="gp">...</span> <span class="gp">>>> </span><span class="n">c</span> <span class="o">=</span> <span class="n">C</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">c</span><span class="o">.</span><span class="n">method</span><span class="o">.</span><span class="n">whoami</span> <span class="o">=</span> <span class="s">'my name is method'</span> <span class="c"># can't set on the method</span> <span class="gt">Traceback (most recent call last):</span> File <span class="nb">"<stdin>"</span>, line <span class="m">1</span>, in <span class="n"><module></span> <span class="gr">AttributeError</span>: <span class="n">'instancemethod' object has no attribute 'whoami'</span> <span class="gp">>>> </span><span class="n">c</span><span class="o">.</span><span class="n">method</span><span class="o">.</span><span class="n">im_func</span><span class="o">.</span><span class="n">whoami</span> <span class="o">=</span> <span class="s">'my name is method'</span> <span class="gp">>>> </span><span class="n">c</span><span class="o">.</span><span class="n">method</span><span class="o">.</span><span class="n">whoami</span> <span class="go">'my name is method'</span> </pre></div> </div> <p>See <a class="reference internal" href="../reference/datamodel.html#types"><em>The standard type hierarchy</em></a> for more information.</p> </div> <div class="section" id="code-objects"> <span id="bltin-code-objects"></span><h3>5.12.5. Code Objects<a class="headerlink" href="#code-objects" title="Permalink to this headline">¶</a></h3> <span class="target" id="index-38"></span><p id="index-39">Code objects are used by the implementation to represent “pseudo-compiled” executable Python code such as a function body. They differ from function objects because they don’t contain a reference to their global execution environment. Code objects are returned by the built-in <a class="reference internal" href="functions.html#compile" title="compile"><tt class="xref py py-func docutils literal"><span class="pre">compile()</span></tt></a> function and can be extracted from function objects through their <tt class="xref py py-attr docutils literal"><span class="pre">func_code</span></tt> attribute. See also the <a class="reference internal" href="code.html#module-code" title="code: Facilities to implement read-eval-print loops."><tt class="xref py py-mod docutils literal"><span class="pre">code</span></tt></a> module.</p> <p id="index-40">A code object can be executed or evaluated by passing it (instead of a source string) to the <a class="reference internal" href="../reference/simple_stmts.html#exec"><tt class="xref std std-keyword docutils literal"><span class="pre">exec</span></tt></a> statement or the built-in <a class="reference internal" href="functions.html#eval" title="eval"><tt class="xref py py-func docutils literal"><span class="pre">eval()</span></tt></a> function.</p> <p>See <a class="reference internal" href="../reference/datamodel.html#types"><em>The standard type hierarchy</em></a> for more information.</p> </div> <div class="section" id="type-objects"> <span id="bltin-type-objects"></span><h3>5.12.6. Type Objects<a class="headerlink" href="#type-objects" title="Permalink to this headline">¶</a></h3> <p id="index-41">Type objects represent the various object types. An object’s type is accessed by the built-in function <a class="reference internal" href="functions.html#type" title="type"><tt class="xref py py-func docutils literal"><span class="pre">type()</span></tt></a>. There are no special operations on types. The standard module <a class="reference internal" href="types.html#module-types" title="types: Names for built-in types."><tt class="xref py py-mod docutils literal"><span class="pre">types</span></tt></a> defines names for all standard built-in types.</p> <p>Types are written like this: <tt class="docutils literal"><span class="pre"><type</span> <span class="pre">'int'></span></tt>.</p> </div> <div class="section" id="the-null-object"> <span id="bltin-null-object"></span><h3>5.12.7. The Null Object<a class="headerlink" href="#the-null-object" title="Permalink to this headline">¶</a></h3> <p>This object is returned by functions that don’t explicitly return a value. It supports no special operations. There is exactly one null object, named <tt class="docutils literal"><span class="pre">None</span></tt> (a built-in name).</p> <p>It is written as <tt class="docutils literal"><span class="pre">None</span></tt>.</p> </div> <div class="section" id="the-ellipsis-object"> <span id="bltin-ellipsis-object"></span><h3>5.12.8. The Ellipsis Object<a class="headerlink" href="#the-ellipsis-object" title="Permalink to this headline">¶</a></h3> <p>This object is used by extended slice notation (see <a class="reference internal" href="../reference/expressions.html#slicings"><em>Slicings</em></a>). It supports no special operations. There is exactly one ellipsis object, named <a class="reference internal" href="constants.html#Ellipsis" title="Ellipsis"><tt class="xref py py-const docutils literal"><span class="pre">Ellipsis</span></tt></a> (a built-in name).</p> <p>It is written as <tt class="docutils literal"><span class="pre">Ellipsis</span></tt>. When in a subscript, it can also be written as <tt class="docutils literal"><span class="pre">...</span></tt>, for example <tt class="docutils literal"><span class="pre">seq[...]</span></tt>.</p> </div> <div class="section" id="the-notimplemented-object"> <h3>5.12.9. The NotImplemented Object<a class="headerlink" href="#the-notimplemented-object" title="Permalink to this headline">¶</a></h3> <p>This object is returned from comparisons and binary operations when they are asked to operate on types they don’t support. See <a class="reference internal" href="../reference/expressions.html#comparisons"><em>Comparisons</em></a> for more information.</p> <p>It is written as <tt class="docutils literal"><span class="pre">NotImplemented</span></tt>.</p> </div> <div class="section" id="boolean-values"> <h3>5.12.10. Boolean Values<a class="headerlink" href="#boolean-values" title="Permalink to this headline">¶</a></h3> <p>Boolean values are the two constant objects <tt class="docutils literal"><span class="pre">False</span></tt> and <tt class="docutils literal"><span class="pre">True</span></tt>. They are used to represent truth values (although other values can also be considered false or true). In numeric contexts (for example when used as the argument to an arithmetic operator), they behave like the integers 0 and 1, respectively. The built-in function <a class="reference internal" href="functions.html#bool" title="bool"><tt class="xref py py-func docutils literal"><span class="pre">bool()</span></tt></a> can be used to convert any value to a Boolean, if the value can be interpreted as a truth value (see section <a class="reference internal" href="#truth"><em>Truth Value Testing</em></a> above).</p> <p id="index-42">They are written as <tt class="docutils literal"><span class="pre">False</span></tt> and <tt class="docutils literal"><span class="pre">True</span></tt>, respectively.</p> </div> <div class="section" id="internal-objects"> <span id="typesinternal"></span><h3>5.12.11. Internal Objects<a class="headerlink" href="#internal-objects" title="Permalink to this headline">¶</a></h3> <p>See <a class="reference internal" href="../reference/datamodel.html#types"><em>The standard type hierarchy</em></a> for this information. It describes stack frame objects, traceback objects, and slice objects.</p> </div> </div> <div class="section" id="special-attributes"> <span id="specialattrs"></span><h2>5.13. Special Attributes<a class="headerlink" href="#special-attributes" title="Permalink to this headline">¶</a></h2> <p>The implementation adds a few special read-only attributes to several object types, where they are relevant. Some of these are not reported by the <a class="reference internal" href="functions.html#dir" title="dir"><tt class="xref py py-func docutils literal"><span class="pre">dir()</span></tt></a> built-in function.</p> <dl class="attribute"> <dt id="object.__dict__"> <tt class="descclassname">object.</tt><tt class="descname">__dict__</tt><a class="headerlink" href="#object.__dict__" title="Permalink to this definition">¶</a></dt> <dd><p>A dictionary or other mapping object used to store an object’s (writable) attributes.</p> </dd></dl> <dl class="attribute"> <dt id="object.__methods__"> <tt class="descclassname">object.</tt><tt class="descname">__methods__</tt><a class="headerlink" href="#object.__methods__" title="Permalink to this definition">¶</a></dt> <dd><p class="deprecated"> <span class="versionmodified">Deprecated since version 2.2: </span>Use the built-in function <a class="reference internal" href="functions.html#dir" title="dir"><tt class="xref py py-func docutils literal"><span class="pre">dir()</span></tt></a> to get a list of an object’s attributes. This attribute is no longer available.</p> </dd></dl> <dl class="attribute"> <dt id="object.__members__"> <tt class="descclassname">object.</tt><tt class="descname">__members__</tt><a class="headerlink" href="#object.__members__" title="Permalink to this definition">¶</a></dt> <dd><p class="deprecated"> <span class="versionmodified">Deprecated since version 2.2: </span>Use the built-in function <a class="reference internal" href="functions.html#dir" title="dir"><tt class="xref py py-func docutils literal"><span class="pre">dir()</span></tt></a> to get a list of an object’s attributes. This attribute is no longer available.</p> </dd></dl> <dl class="attribute"> <dt id="instance.__class__"> <tt class="descclassname">instance.</tt><tt class="descname">__class__</tt><a class="headerlink" href="#instance.__class__" title="Permalink to this definition">¶</a></dt> <dd><p>The class to which a class instance belongs.</p> </dd></dl> <dl class="attribute"> <dt id="class.__bases__"> <tt class="descclassname">class.</tt><tt class="descname">__bases__</tt><a class="headerlink" href="#class.__bases__" title="Permalink to this definition">¶</a></dt> <dd><p>The tuple of base classes of a class object.</p> </dd></dl> <dl class="attribute"> <dt id="class.__name__"> <tt class="descclassname">class.</tt><tt class="descname">__name__</tt><a class="headerlink" href="#class.__name__" title="Permalink to this definition">¶</a></dt> <dd><p>The name of the class or type.</p> </dd></dl> <p>The following attributes are only supported by <a class="reference internal" href="../glossary.html#term-new-style-class"><em class="xref std std-term">new-style class</em></a>es.</p> <dl class="attribute"> <dt id="class.__mro__"> <tt class="descclassname">class.</tt><tt class="descname">__mro__</tt><a class="headerlink" href="#class.__mro__" title="Permalink to this definition">¶</a></dt> <dd><p>This attribute is a tuple of classes that are considered when looking for base classes during method resolution.</p> </dd></dl> <dl class="method"> <dt id="class.mro"> <tt class="descclassname">class.</tt><tt class="descname">mro</tt><big>(</big><big>)</big><a class="headerlink" href="#class.mro" title="Permalink to this definition">¶</a></dt> <dd><p>This method can be overridden by a metaclass to customize the method resolution order for its instances. It is called at class instantiation, and its result is stored in <a class="reference internal" href="#class.__mro__" title="class.__mro__"><tt class="xref py py-attr docutils literal"><span class="pre">__mro__</span></tt></a>.</p> </dd></dl> <dl class="method"> <dt id="class.__subclasses__"> <tt class="descclassname">class.</tt><tt class="descname">__subclasses__</tt><big>(</big><big>)</big><a class="headerlink" href="#class.__subclasses__" title="Permalink to this definition">¶</a></dt> <dd><p>Each new-style class keeps a list of weak references to its immediate subclasses. This method returns a list of all those references still alive. Example:</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="nb">int</span><span class="o">.</span><span class="n">__subclasses__</span><span class="p">()</span> <span class="go">[<type 'bool'>]</span> </pre></div> </div> </dd></dl> <p class="rubric">Footnotes</p> <table class="docutils footnote" frame="void" id="id12" rules="none"> <colgroup><col class="label" /><col /></colgroup> <tbody valign="top"> <tr><td class="label"><a class="fn-backref" href="#id1">[1]</a></td><td>Additional information on these special methods may be found in the Python Reference Manual (<a class="reference internal" href="../reference/datamodel.html#customization"><em>Basic customization</em></a>).</td></tr> </tbody> </table> <table class="docutils footnote" frame="void" id="id13" rules="none"> <colgroup><col class="label" /><col /></colgroup> <tbody valign="top"> <tr><td class="label"><a class="fn-backref" href="#id2">[2]</a></td><td>As a consequence, the list <tt class="docutils literal"><span class="pre">[1,</span> <span class="pre">2]</span></tt> is considered equal to <tt class="docutils literal"><span class="pre">[1.0,</span> <span class="pre">2.0]</span></tt>, and similarly for tuples.</td></tr> </tbody> </table> <table class="docutils footnote" frame="void" id="id14" rules="none"> <colgroup><col class="label" /><col /></colgroup> <tbody valign="top"> <tr><td class="label"><a class="fn-backref" href="#id4">[3]</a></td><td>They must have since the parser can’t tell the type of the operands.</td></tr> </tbody> </table> <table class="docutils footnote" frame="void" id="id15" rules="none"> <colgroup><col class="label" /><col /></colgroup> <tbody valign="top"> <tr><td class="label">[4]</td><td><em>(<a class="fn-backref" href="#id6">1</a>, <a class="fn-backref" href="#id7">2</a>, <a class="fn-backref" href="#id8">3</a>, <a class="fn-backref" href="#id9">4</a>)</em> Cased characters are those with general category property being one of “Lu” (Letter, uppercase), “Ll” (Letter, lowercase), or “Lt” (Letter, titlecase).</td></tr> </tbody> </table> <table class="docutils footnote" frame="void" id="id16" rules="none"> <colgroup><col class="label" /><col /></colgroup> <tbody valign="top"> <tr><td class="label"><a class="fn-backref" href="#id10">[5]</a></td><td>To format only a tuple you should therefore provide a singleton tuple whose only element is the tuple to be formatted.</td></tr> </tbody> </table> <table class="docutils footnote" frame="void" id="id17" rules="none"> <colgroup><col class="label" /><col /></colgroup> <tbody valign="top"> <tr><td class="label"><a class="fn-backref" href="#id11">[6]</a></td><td>The advantage of leaving the newline on is that returning an empty string is then an unambiguous EOF indication. It is also possible (in cases where it might matter, for example, if you want to make an exact copy of a file while scanning its lines) to tell whether the last line of a file ended in a newline or not (yes this happens!).</td></tr> </tbody> </table> </div> </div> </div> </div> </div> <div class="sphinxsidebar"> <div class="sphinxsidebarwrapper"> <h3><a href="../contents.html">Table Of Contents</a></h3> <ul> <li><a class="reference internal" href="#">5. Built-in Types</a><ul> <li><a class="reference internal" href="#truth-value-testing">5.1. Truth Value Testing</a></li> <li><a class="reference internal" href="#boolean-operations-and-or-not">5.2. Boolean Operations — <tt class="docutils literal"><span class="pre">and</span></tt>, <tt class="docutils literal"><span class="pre">or</span></tt>, <tt class="docutils literal"><span class="pre">not</span></tt></a></li> <li><a class="reference internal" href="#comparisons">5.3. Comparisons</a></li> <li><a class="reference internal" href="#numeric-types-int-float-long-complex">5.4. Numeric Types — <tt class="docutils literal"><span class="pre">int</span></tt>, <tt class="docutils literal"><span class="pre">float</span></tt>, <tt class="docutils literal"><span class="pre">long</span></tt>, <tt class="docutils literal"><span class="pre">complex</span></tt></a><ul> <li><a class="reference internal" href="#bitwise-operations-on-integer-types">5.4.1. Bitwise Operations on Integer Types</a></li> <li><a class="reference internal" href="#additional-methods-on-integer-types">5.4.2. Additional Methods on Integer Types</a></li> <li><a class="reference internal" href="#additional-methods-on-float">5.4.3. Additional Methods on Float</a></li> </ul> </li> <li><a class="reference internal" href="#iterator-types">5.5. Iterator Types</a><ul> <li><a class="reference internal" href="#generator-types">5.5.1. Generator Types</a></li> </ul> </li> <li><a class="reference internal" href="#sequence-types-str-unicode-list-tuple-bytearray-buffer-xrange">5.6. Sequence Types — <tt class="docutils literal"><span class="pre">str</span></tt>, <tt class="docutils literal"><span class="pre">unicode</span></tt>, <tt class="docutils literal"><span class="pre">list</span></tt>, <tt class="docutils literal"><span class="pre">tuple</span></tt>, <tt class="docutils literal"><span class="pre">bytearray</span></tt>, <tt class="docutils literal"><span class="pre">buffer</span></tt>, <tt class="docutils literal"><span class="pre">xrange</span></tt></a><ul> <li><a class="reference internal" href="#string-methods">5.6.1. String Methods</a></li> <li><a class="reference internal" href="#string-formatting-operations">5.6.2. String Formatting Operations</a></li> <li><a class="reference internal" href="#xrange-type">5.6.3. XRange Type</a></li> <li><a class="reference internal" href="#mutable-sequence-types">5.6.4. Mutable Sequence Types</a></li> </ul> </li> <li><a class="reference internal" href="#set-types-set-frozenset">5.7. Set Types — <tt class="docutils literal"><span class="pre">set</span></tt>, <tt class="docutils literal"><span class="pre">frozenset</span></tt></a></li> <li><a class="reference internal" href="#mapping-types-dict">5.8. Mapping Types — <tt class="docutils literal"><span class="pre">dict</span></tt></a><ul> <li><a class="reference internal" href="#dictionary-view-objects">5.8.1. Dictionary view objects</a></li> </ul> </li> <li><a class="reference internal" href="#file-objects">5.9. File Objects</a></li> <li><a class="reference internal" href="#memoryview-type">5.10. memoryview type</a></li> <li><a class="reference internal" href="#context-manager-types">5.11. Context Manager Types</a></li> <li><a class="reference internal" href="#other-built-in-types">5.12. Other Built-in Types</a><ul> <li><a class="reference internal" href="#modules">5.12.1. Modules</a></li> <li><a class="reference internal" href="#classes-and-class-instances">5.12.2. Classes and Class Instances</a></li> <li><a class="reference internal" href="#functions">5.12.3. Functions</a></li> <li><a class="reference internal" href="#methods">5.12.4. Methods</a></li> <li><a class="reference internal" href="#code-objects">5.12.5. Code Objects</a></li> <li><a class="reference internal" href="#type-objects">5.12.6. Type Objects</a></li> <li><a class="reference internal" href="#the-null-object">5.12.7. The Null Object</a></li> <li><a class="reference internal" href="#the-ellipsis-object">5.12.8. The Ellipsis Object</a></li> <li><a class="reference internal" href="#the-notimplemented-object">5.12.9. The NotImplemented Object</a></li> <li><a class="reference internal" href="#boolean-values">5.12.10. Boolean Values</a></li> <li><a class="reference internal" href="#internal-objects">5.12.11. Internal Objects</a></li> </ul> </li> <li><a class="reference internal" href="#special-attributes">5.13. Special Attributes</a></li> </ul> </li> </ul> <h4>Previous topic</h4> <p class="topless"><a href="constants.html" title="previous chapter">4. Built-in Constants</a></p> <h4>Next topic</h4> <p class="topless"><a href="exceptions.html" title="next chapter">6. Built-in Exceptions</a></p> <h3>This Page</h3> <ul class="this-page-menu"> <li><a href="../bugs.html">Report a Bug</a></li> <li><a href="../_sources/library/stdtypes.txt" rel="nofollow">Show Source</a></li> </ul> <div id="searchbox" style="display: none"> <h3>Quick search</h3> <form class="search" action="../search.html" method="get"> <input type="text" name="q" /> <input type="submit" value="Go" /> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> <p class="searchtip" style="font-size: 90%"> Enter search terms or a module, class or function name. </p> </div> <script type="text/javascript">$('#searchbox').show(0);</script> </div> </div> <div class="clearer"></div> </div> <div class="related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" >index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="exceptions.html" title="6. Built-in Exceptions" >next</a> |</li> <li class="right" > <a href="constants.html" title="4. Built-in Constants" >previous</a> |</li> <li><img src="../_static/py.png" alt="" style="vertical-align: middle; margin-top: -1px"/></li> <li><a href="http://www.python.org/">Python</a> »</li> <li> <a href="../index.html">Python 2.7.5 documentation</a> » </li> <li><a href="index.html" >The Python Standard Library</a> »</li> </ul> </div> <div class="footer"> © <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation. <br /> The Python Software Foundation is a non-profit corporation. <a href="http://www.python.org/psf/donations/">Please donate.</a> <br /> Last updated on Jul 03, 2019. <a href="../bugs.html">Found a bug</a>? <br /> Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.1.3. </div> </body> </html>
Close