Skip to main content

Python Language Notes (Overview)

External modules

A listing of frequently used external Python modules (list updated as needed):

ModuleDescription
tbddesc

Standard library modules

A listing of frequently used standard library Python modules (list updated as needed):

ModuleDescription
Data Structures and Algorithms
collectionsContainer datatypes
functoolsHigher-order functions and operations on callable objects
itertoolsFunctions creating iterators for efficient looping
copyShallow and deep copy operations
jsonEncode and decode the JSON format
json.toolA command line to validate and pretty-print JSON
heapqHeap queue algorithm (a.k.a. priority queue)
queueA synchronized queue class
graphlibFunctionality to operate with graph-like structures
reRegular expression operations
stringCommon string operations
cmathMathematical functions for complex numbers
mathMathematical functions (sin() etc.)
randomGenerate pseudo-random numbers with various common distributions
statisticsMathematical statistics functions
Dates and Times
calendarFunctions for working with calendars, including some emulation of the Unix cal program
datetimeBasic date and time types
Debugging and Testing
difflibHelpers for computing differences between objects
inspectExtract information and source code from live objects
loggingFlexible event logging system for applications
pdbThe Python debugger for interactive interpreters
timeTime access and conversions
timeitMeasure the execution time of small code snippets
unittestUnit testing framework for Python
unittest.mockMock object library
warningsIssue warning messages and control their disposition
Documentation
doctestTest pieces of code within docstrings
pydocDocumentation generator and online help system
typesNames for built-in types
typingSupport for type hints (see :pep:484)
Encoding and Decoding
base64RFC 3548: Base16, Base32, Base64 Data Encodings; Base85 and Ascii85
hashlibSecure hash and message digest algorithms
uuidUUID objects (universally unique identifiers) according to RFC 4122
File Manipulation and Input/Output
asyncioAsynchronous I/O
csvWrite and read tabular data to and from delimited files
ioCore tools for working with streams
osMiscellaneous operating system interfaces
pathlibObject-oriented filesystem paths
sysAccess system-specific parameters and functions
sysconfigPython's configuration information
tempfileGenerate temporary files and directories
textwrapText wrapping and filling
Reference
__main__The environment where the top-level script is run
dataclassesGenerate special methods on user-defined classes
emailPackage supporting the parsing, manipulating, and generating email messages
globUnix shell style pathname pattern expansion
keywordTest whether a string is a keyword in Python
venvCreation of virtual environments

Complete standard library module index

ModuleDescription
-
__future__Future statement definitions
__main__The environment where the top-level script is run
_threadLow-level threading API
A
abcAbstract base classes according to :pep:3119
aifcRead and write audio files in AIFF or AIFC format
argparseCommand-line option and argument parsing library
arraySpace efficient arrays of uniformly typed numeric values
astAbstract Syntax Tree classes and manipulation
asynchatSupport for asynchronous command/response protocols
asyncioAsynchronous I/O
asyncoreA base class for developing asynchronous socket handling services
atexitRegister and execute cleanup functions
audioopManipulate raw audio data
B
base64RFC 3548: Base16, Base32, Base64 Data Encodings; Base85 and Ascii85
bdbDebugger framework
binasciiTools for converting between binary and various ASCII-encoded binary representations
binhexEncode and decode files in binhex4 format
bisectArray bisection algorithms for binary searching
builtinsThe module that provides the built-in namespace
bz2Interfaces for bzip2 compression and decompression
C
calendarFunctions for working with calendars, including some emulation of the Unix cal program
cgiHelpers for running Python scripts via the Common Gateway Interface
cgitbConfigurable traceback handler for CGI scripts
chunkModule to read IFF chunks
cmathMathematical functions for complex numbers
cmdBuild line-oriented command interpreters
codeFacilities to implement read-eval-print loops
codecsEncode and decode data and streams
codeopCompile (possibly incomplete) Python code
collectionsContainer datatypes
collections.abcAbstract base classes for containers
colorsysConversion functions between RGB and other color systems
compileallTools for byte-compiling all Python source files in a directory tree
concurrent
concurrent.futuresExecute computations concurrently using threads or processes
configparserConfiguration file parser
contextlibUtilities for with-statement contexts
contextvarsContext Variables
copyShallow and deep copy operations
copyregRegister pickle support functions
cProfile
crypt (Unix)The crypt() function used to check Unix passwords
csvWrite and read tabular data to and from delimited files
ctypesA foreign function library for Python
curses (Unix)An interface to the curses library, providing portable terminal handling
curses.asciiConstants and set-membership functions for ASCII characters
curses.panelA panel stack extension that adds depth to curses windows
curses.textpadEmacs-like input editing in a curses window
D
dataclassesGenerate special methods on user-defined classes
datetimeBasic date and time types
dbmInterfaces to various Unix "database" formats
dbm.dumbPortable implementation of the simple DBM interface
dbm.gnu (Unix)GNU's reinterpretation of dbm
dbm.ndbm (Unix)The standard "database" interface, based on ndbm
decimalImplementation of the General Decimal Arithmetic Specification
difflibHelpers for computing differences between objects
disDisassembler for Python bytecode
distutilsSupport for building and installing Python modules into an existing Python installation
distutils.archive_utilUtility functions for creating archive files (tarballs, zip files, ...)
distutils.bcppcompiler
distutils.ccompilerAbstract CCompiler class
distutils.cmdProvides the abstract base class :class:~distutils.cmd.Command. This class is subclassed by the modules in the distutils.command subpackage.
distutils.commandContains one module for each standard Distutils command
distutils.command.bdistBuild a binary installer for a package
distutils.command.bdist_dumbBuild a "dumb" installer - a simple archive of files
distutils.command.bdist_msiBuild a binary distribution as a Windows MSI file
distutils.command.bdist_packagerAbstract base class for packagers
distutils.command.bdist_rpmBuild a binary distribution as a Redhat RPM and SRPM
distutils.command.bdist_wininstBuild a Windows installer
distutils.command.buildBuild all files of a package
distutils.command.build_clibBuild any C libraries in a package
distutils.command.build_extBuild any extensions in a package
distutils.command.build_pyBuild the .py/.pyc files of a package
distutils.command.build_scriptsBuild the scripts of a package
distutils.command.checkCheck the meta-data of a package
distutils.command.cleanClean a package build area
distutils.command.configPerform package configuration
distutils.command.installInstall a package
distutils.command.install_dataInstall data files from a package
distutils.command.install_headersInstall C/C++ header files from a package
distutils.command.install_libInstall library files from a package
distutils.command.install_scriptsInstall script files from a package
distutils.command.registerRegister a module with the Python Package Index
distutils.command.sdistBuild a source distribution
distutils.coreThe core Distutils functionality
distutils.cygwinccompiler
distutils.debugProvides the debug flag for distutils
distutils.dep_utilUtility functions for simple dependency checking
distutils.dir_utilUtility functions for operating on directories and directory trees
distutils.distProvides the Distribution class, which represents the module distribution being built/installed/distributed
distutils.errorsProvides standard distutils exceptions
distutils.extensionProvides the Extension class, used to describe C/C++ extension modules in setup scripts
distutils.fancy_getoptAdditional getopt functionality
distutils.file_utilUtility functions for operating on single files
distutils.filelistThe FileList class, used for poking about the file system and building lists of files.
distutils.logA simple logging mechanism, :pep:282-style
distutils.msvccompilerMicrosoft Compiler
distutils.spawnProvides the spawn() function
distutils.sysconfigLow-level access to configuration information of the Python interpreter
distutils.text_fileProvides the TextFile class, a simple interface to text files
distutils.unixccompilerUNIX C Compiler
distutils.utilMiscellaneous other utility functions
distutils.versionImplements classes that represent module version numbers
doctestTest pieces of code within docstrings
E
emailPackage supporting the parsing, manipulating, and generating email messages
email.charsetCharacter Sets
email.contentmanagerStoring and Retrieving Content from MIME Parts
email.encodersEncoders for email message payloads
email.errorsThe exception classes used by the email package
email.generatorGenerate flat text email messages from a message structure
email.headerRepresenting non-ASCII headers
email.headerregistryAutomatic Parsing of headers based on the field name
email.iteratorsIterate over a message object tree
email.messageThe base class representing email messages
email.mimeBuild MIME messages
email.parserParse flat text email messages to produce a message object structure
email.policyControlling the parsing and generating of messages
email.utilsMiscellaneous email package utilities
encodings
encodings.idnaInternationalized Domain Names implementation
encodings.mbcsWindows ANSI codepage
encodings.utf_8_sigUTF-8 codec with BOM signature
ensurepipBootstrapping the "pip" installer into an existing Python installation or virtual environment
enumImplementation of an enumeration class
errnoStandard errno system symbols
F
faulthandlerDump the Python traceback
fcntl (Unix)The fcntl() and ioctl() system calls
filecmpCompare files efficiently
fileinputLoop over standard input or a list of files
fnmatchUnix shell style filename pattern matching
formatterDeprecated: Generic output formatter and device interface
fractionsRational numbers
ftplibFTP protocol client (requires sockets)
functoolsHigher-order functions and operations on callable objects
G
gcInterface to the cycle-detecting garbage collector
getoptPortable parser for command line options; support both short and long option names
getpassPortable reading of passwords and retrieval of the userid
gettextMultilingual internationalization services
globUnix shell style pathname pattern expansion
graphlibFunctionality to operate with graph-like structures
grp (Unix)The group database (getgrnam() and friends)
gzipInterfaces for gzip compression and decompression using file objects
H
hashlibSecure hash and message digest algorithms
heapqHeap queue algorithm (a.k.a. priority queue)
hmacKeyed-Hashing for Message Authentication (HMAC) implementation
htmlHelpers for manipulating HTML
html.entitiesDefinitions of HTML general entities
html.parserA simple parser that can handle HTML and XHTML
httpHTTP status codes and messages
http.clientHTTP and HTTPS protocol client (requires sockets)
http.cookiejarClasses for automatic handling of HTTP cookies
http.cookiesSupport for HTTP state management (cookies)
http.serverHTTP server and request handlers
I
imaplibIMAP4 protocol client (requires sockets)
imghdrDetermine the type of image contained in a file or byte stream
impDeprecated: Access the implementation of the import statement
importlibThe implementation of the import machinery
importlib.abcAbstract base classes related to import
importlib.machineryImporters and path hooks
importlib.metadataThe implementation of the importlib metadata
importlib.resourcesPackage resource reading, opening, and access
importlib.utilUtility code for importers
inspectExtract information and source code from live objects
ioCore tools for working with streams
ipaddressIPv4/IPv6 manipulation library
itertoolsFunctions creating iterators for efficient looping
J
jsonEncode and decode the JSON format
json.toolA command line to validate and pretty-print JSON
K
keywordTest whether a string is a keyword in Python
L
lib2to3The 2to3 library
linecacheProvides random access to individual lines from text files
localeInternationalization services
loggingFlexible event logging system for applications
logging.configConfiguration of the logging module
logging.handlersHandlers for the logging module
lzmaA Python wrapper for the liblzma compression library
M
mailboxManipulate mailboxes in various formats
mailcapMailcap file handling
marshalConvert Python objects to streams of bytes and back (with different constraints)
mathMathematical functions (sin() etc.)
mimetypesMapping of filename extensions to MIME types
mmapInterface to memory-mapped files for Unix and Windows
modulefinderFind modules used by a script
msilib (Windows)Creation of Microsoft Installer files, and CAB files
msvcrt (Windows)Miscellaneous useful routines from the MS VC++ runtime
multiprocessingProcess-based parallelism
multiprocessing.connectionAPI for dealing with sockets
multiprocessing.dummyDumb wrapper around threading
multiprocessing.managersShare data between process with shared objects
multiprocessing.poolCreate pools of processes
multiprocessing.shared_memoryProvides shared memory for direct access across processes
multiprocessing.sharedctypesAllocate ctypes objects from shared memory
N
netrcLoading of .netrc files
nis (Unix)Interface to Sun's NIS (Yellow Pages) library
nntplibNNTP protocol client (requires sockets)
numbersNumeric abstract base classes (Complex, Real, Integral, etc.)
O
operatorFunctions corresponding to the standard operators
optparseDeprecated: Command-line option parsing library
osMiscellaneous operating system interfaces
os.pathOperations on pathnames
ossaudiodev(Linux, FreeBSD) Access to OSS-compatible audio devices
P
parserAccess parse trees for Python source code
pathlibObject-oriented filesystem paths
pdbThe Python debugger for interactive interpreters
pickleConvert Python objects to streams of bytes and back
pickletoolsContains extensive comments about the pickle protocols and pickle-machine opcodes, as well as some useful functions
pipes (Unix)A Python interface to Unix shell pipelines
pkgutilUtilities for the import system
platformRetrieves as much platform identifying data as possible
plistlibGenerate and parse Apple plist files
poplibPOP3 protocol client (requires sockets)
posix (Unix)The most common POSIX system calls (normally used via module os)
pprintData pretty printer
profilePython source profiler
pstatsStatistics object for use with the profiler
pty (Linux)Pseudo-Terminal Handling for Linux
pwd (Unix)The password database (getpwnam() and friends)
py_compileGenerate byte-code files from Python source files
pyclbrSupports information extraction for a Python module browser
pydocDocumentation generator and online help system
Q
queueA synchronized queue class
quopriEncode and decode files using the MIME quoted-printable encoding
R
randomGenerate pseudo-random numbers with various common distributions
reRegular expression operations
readline (Unix)GNU readline support for Python
reprlibAlternate repr() implementation with size limits
resource (Unix)An interface to provide resource usage information on the current process
rlcompleterPython identifier completion, suitable for the GNU readline library
runpyLocate and run Python modules without importing them first
S
schedGeneral purpose event scheduler
secretsGenerate secure random numbers for managing secrets
selectWait for I/O completion on multiple streams
selectorsHigh-level I/O multiplexing
shelvePython object persistence
shlexSimple lexical analysis for Unix shell-like languages
shutilHigh-level file operations, including copying
signalSet handlers for asynchronous events
siteModule responsible for site-specific configuration
smtpdA SMTP server implementation in Python
smtplibSMTP protocol client (requires sockets)
sndhdrDetermine type of a sound file
socketLow-level networking interface
socketserverA framework for network servers
spwd (Unix)The shadow password database (getspnam() and friends)
sqlite3A DB-API 2.0 implementation using SQLite 3.x
sslTLS/SSL wrapper for socket objects
statUtilities for interpreting the results of os.stat(), os.lstat() and os.fstat()
statisticsMathematical statistics functions
stringCommon string operations
stringprepString preparation, as per RFC 3453
structInterpret bytes as packed binary data
subprocessSubprocess management
sunauProvide an interface to the Sun AU sound format
symbolConstants representing internal nodes of the parse tree
symtableInterface to the compiler's internal symbol tables
sysAccess system-specific parameters and functions
sysconfigPython's configuration information
syslog (Unix)An interface to the Unix syslog library routines
T
tabnannyTool for detecting white space related problems in Python source files in a directory tree
tarfileRead and write tar-format archive files
telnetlibTelnet client class
tempfileGenerate temporary files and directories
termios (Unix)POSIX style tty control
testRegression tests package containing the testing suite for Python
test.supportSupport for Python's regression test suite
test.support.bytecode_helperSupport tools for testing correct bytecode generation
test.support.script_helperSupport for Python's script execution tests
test.support.socket_helperSupport for socket tests
textwrapText wrapping and filling
threadingThread-based parallelism
timeTime access and conversions
timeitMeasure the execution time of small code snippets
tkinterInterface to Tcl/Tk for graphical user interfaces
tkinter.colorchooser (Tk)Color choosing dialog
tkinter.commondialog (Tk)Tkinter base class for dialogs
tkinter.dnd (Tk)Tkinter drag-and-drop interface
tkinter.filedialog (Tk)Dialog classes for file selection
tkinter.font (Tk)Tkinter font-wrapping class
tkinter.messagebox (Tk)Various types of alert dialogs
tkinter.scrolledtext (Tk)Text widget with a vertical scroll bar
tkinter.simpledialog (Tk)Simple dialog windows
tkinter.tixTk Extension Widgets for Tkinter
tkinter.ttkTk themed widget set
tokenConstants representing terminal nodes of the parse tree
tokenizeLexical scanner for Python source code
traceTrace or track Python statement execution
tracebackPrint or retrieve a stack traceback
tracemallocTrace memory allocations
tty (Unix)Utility functions that perform common terminal control operations
turtleAn educational framework for simple graphics applications
turtledemoA viewer for example turtle scripts
typesNames for built-in types
typingSupport for type hints (see :pep:484)
U
unicodedataAccess the Unicode Database
unittestUnit testing framework for Python
unittest.mockMock object library
urllib
urllib.errorException classes raised by urllib.request
urllib.parseParse URLs into or assemble them from components
urllib.requestExtensible library for opening URLs
urllib.responseResponse classes used by urllib
urllib.robotparserLoad a robots.txt file and answer questions about fetchability of other URLs
uuEncode and decode files in uuencode format
uuidUUID objects (universally unique identifiers) according to RFC 4122
V
venvCreation of virtual environments
W
warningsIssue warning messages and control their disposition
waveProvide an interface to the WAV sound format
weakrefSupport for weak references and weak dictionaries
webbrowserEasy-to-use controller for Web browsers
winreg (Windows)Routines and objects for manipulating the Windows registry
winsound (Windows)Access to the sound-playing machinery for Windows
wsgirefWSGI Utilities and Reference Implementation
wsgiref.handlersWSGI server/gateway base classes
wsgiref.headersWSGI response header tools
wsgiref.simple_serverA simple WSGI HTTP server
wsgiref.utilWSGI environment utilities
wsgiref.validateWSGI conformance checker
X
xdrlibEncoders and decoders for the External Data Representation (XDR)
xmlPackage containing XML processing modules
xml.domDocument Object Model API for Python
xml.dom.minidomMinimal Document Object Model (DOM) implementation
xml.dom.pulldomSupport for building partial DOM trees from SAX events
xml.etree.ElementTreeImplementation of the ElementTree API
xml.parsers.expatAn interface to the Expat non-validating XML parser
xml.parsers.expat.errors
xml.parsers.expat.model
xml.saxPackage containing SAX2 base classes and convenience functions
xml.sax.handlerBase classes for SAX event handlers
xml.sax.saxutilsConvenience functions and classes for use with SAX
xml.sax.xmlreaderInterface which SAX-compliant XML parsers must implement
xmlrpc
xmlrpc.clientXML-RPC client access
xmlrpc.serverBasic XML-RPC server implementations
Z
zipappManage executable Python zip archives
zipfileRead and write ZIP-format archive files
zipimportSupport for importing Python modules from ZIP archives
zlibLow-level interface to compression and decompression routines compatible with gzip
zoneinfoIANA time zone support

Built-in functions

FunctionDescription
abs()Returns the absolute value of a number
all()Returns True if all items in an iterable object are true
any()Returns True if any item in an iterable object is true
ascii()Returns a readable version of an object. Replaces none-ascii characters with escape character
bin()Returns the binary version of a number
bool()Returns the boolean value of the specified object
bytearray()Returns an array of bytes
bytes()Returns a bytes object
callable()Returns True if the specified object is callable, otherwise False
chr()Returns a character from the specified Unicode code.
classmethod()Converts a method into a class method
compile()Returns the specified source as an object, ready to be executed
complex()Returns a complex number
delattr()Deletes the specified attribute (property or method) from the specified object
dict()Returns a dictionary (Array)
dir()Returns a list of the specified object's properties and methods
divmod()Returns the quotient and the remainder when argument1 is divided by argument2
enumerate()Takes a collection (e.g. a tuple) and returns it as an enumerate object
eval()Evaluates and executes an expression
exec()Executes the specified code (or object)
filter()Use a filter function to exclude items in an iterable object
float()Returns a floating point number
format()Formats a specified value
frozenset()Returns a frozenset object
getattr()Returns the value of the specified attribute (property or method)
globals()Returns the current global symbol table as a dictionary
hasattr()Returns True if the specified object has the specified attribute (property/method)
hash()Returns the hash value of a specified object
help()Executes the built-in help system
hex()Converts a number into a hexadecimal value
id()Returns the id of an object
input()Allowing user input
int()Returns an integer number
isinstance()Returns True if a specified object is an instance of a specified object
issubclass()Returns True if a specified class is a subclass of a specified object
iter()Returns an iterator object
len()Returns the length of an object
list()Returns a list
locals()Returns an updated dictionary of the current local symbol table
map()Returns the specified iterator with the specified function applied to each item
max()Returns the largest item in an iterable
memoryview()Returns a memory view object
min()Returns the smallest item in an iterable
next()Returns the next item in an iterable
object()Returns a new object
oct()Converts a number into an octal
open()Opens a file and returns a file object
ord()Convert an integer representing the Unicode of the specified character
pow()Returns the value of x to the power of y
print()Prints to the standard output device
property()Gets, sets, deletes a property
range()Returns a sequence of numbers, starting from 0 and increments by 1 (by default)
repr()Returns a readable version of an object
reversed()Returns a reversed iterator
round()Rounds a numbers
set()Returns a new set object
setattr()Sets an attribute (property/method) of an object
slice()Returns a slice object
sorted()Returns a sorted list
@staticmethod()Converts a method into a static method
str()Returns a string object
sum()Sums the items of an iterator
super()Returns an object that represents the parent class
tuple()Returns a tuple
type()Returns the type of an object
vars()Returns the dict property of an object
zip()Returns an iterator, from two or more iterators

String methods

MethodDescription
capitalize()Converts the first character to upper case
casefold()Converts string into lower case
center()Returns a centered string
count()Returns the number of times a specified value occurs in a string
encode()Returns an encoded version of the string
endswith()Returns true if the string ends with the specified value
expandtabs()Sets the tab size of the string
find()Searches the string for a specified value and returns the position of where it was found
format()Formats specified values in a string
format_map()Formats specified values in a string
index()Searches the string for a specified value and returns the position of where it was found
isalnum()Returns True if all characters in the string are alphanumeric
isalpha()Returns True if all characters in the string are in the alphabet
isdecimal()Returns True if all characters in the string are decimals
isdigit()Returns True if all characters in the string are digits
isidentifier()Returns True if the string is an identifier
islower()Returns True if all characters in the string are lower case
isnumeric()Returns True if all characters in the string are numeric
isprintable()Returns True if all characters in the string are printable
isspace()Returns True if all characters in the string are whitespaces
istitle()Returns True if the string follows the rules of a title
isupper()Returns True if all characters in the string are upper case
join()Joins the elements of an iterable to the end of the string
ljust()Returns a left justified version of the string
lower()Converts a string into lower case
lstrip()Returns a left trim version of the string
maketrans()Returns a translation table to be used in translations
partition()Returns a tuple where the string is parted into three parts
replace()Returns a string where a specified value is replaced with a specified value
rfind()Searches the string for a specified value and returns the last position of where it was found
rindex()Searches the string for a specified value and returns the last position of where it was found
rjust()Returns a right justified version of the string
rpartition()Returns a tuple where the string is parted into three parts
rsplit()Splits the string at the specified separator, and returns a list
rstrip()Returns a right trim version of the string
split()Splits the string at the specified separator, and returns a list
splitlines()Splits the string at line breaks and returns a list
startswith()Returns true if the string starts with the specified value
strip()Returns a trimmed version of the string
swapcase()Swaps cases, lower case becomes upper case and vice versa
title()Converts the first character of each word to upper case
translate()Returns a translated string
upper()Converts a string into upper case
zfill()Fills the string with a specified number of 0 values at the beginning

List methods

MethodDescription
append()Adds an element at the end of the list
clear()Removes all the elements from the list
copy()Returns a copy of the list
count()Returns the number of elements with the specified value
extend()Add the elements of a list (or any iterable), to the end of the current list
index()Returns the index of the first element with the specified value
insert()Adds an element at the specified position
pop()Removes the element at the specified position
remove()Removes the first item with the specified value
reverse()Reverses the order of the list
sort()Sorts the list

Dictionary methods

MethodDescription
clear()Removes all the elements from the dictionary
copy()Returns a copy of the dictionary
fromkeys()Returns a dictionary with the specified keys and value
get()Returns the value of the specified key
items()Returns a list containing a tuple for each key value pair
keys()Returns a list containing the dictionary's keys
pop()Removes the element with the specified key
popitem()Removes the last inserted key-value pair
setdefault()Returns the value of the specified key. If the key does not exist: insert the key, with the specified value
update()Updates the dictionary with the specified key-value pairs
values()Returns a list of all the values in the dictionary

Tuple methods

MethodDescription
count()Returns the number of times a specified value occurs in a tuple
index()Searches the tuple for a specified value and returns the position of where it was found

Set methods

MethodDescription
add()Adds an element to the set
clear()Removes all the elements from the set
copy()Returns a copy of the set
difference()Returns a set containing the difference between two or more sets
difference_update()Removes the items in this set that are also included in another, specified set
discard()Remove the specified item
intersection()Returns a set, that is the intersection of two other sets
intersection_update()Removes the items in this set that are not present in other, specified set(s)
isdisjoint()Returns whether two sets have a intersection or not
issubset()Returns whether another set contains this set or not
issuperset()Returns whether this set contains another set or not
pop()Removes an element from the set
remove()Removes the specified element
symmetric_difference()Returns a set with the symmetric differences of two sets
symmetric_difference_update()inserts the symmetric differences from this set and another
union()Return a set containing the union of sets
update()Update the set with another set, or any other iterable

File methods

MethodDescription
close()Closes the file
detach()Returns the separated raw stream from the buffer
fileno()Returns a number that represents the stream, from the operating system's perspective
flush()Flushes the internal buffer
isatty()Returns whether the file stream is interactive or not
read()Returns the file content
readable()Returns whether the file stream can be read or not
readline()Returns one line from the file
readlines()Returns a list of lines from the file
seek()Change the file position
seekable()Returns whether the file allows us to change the file position
tell()Returns the current file position
truncate()Resizes the file to a specified size
writable()Returns whether the file can be written to or not
write()Writes the specified string to the file
writelines()Writes a list of strings to the file

Keywords

KeywordDescription
andA logical operator
asTo create an alias
assertFor debugging
breakTo break out of a loop
classTo define a class
continueTo continue to the next iteration of a loop
defTo define a function
delTo delete an object
elifUsed in conditional statements, same as else if
elseUsed in conditional statements
exceptUsed with exceptions, what to do when an exception occurs
FalseBoolean value, result of comparison operations
finallyUsed with exceptions, a block of code that will be executed no matter if there is an exception or not
forTo create a for loop
fromTo import specific parts of a module
globalTo declare a global variable
ifTo make a conditional statement
importTo import a module
inTo check if a value is present in a list, tuple, etc.
isTo test if two variables are equal
lambdaTo create an anonymous function
NoneRepresents a null value
nonlocalTo declare a non-local variable
notA logical operator
orA logical operator
passA null statement, a statement that will do nothing
raiseTo raise an exception
returnTo exit a function and return a value
TrueBoolean value, result of comparison operations
tryTo make a try...except statement
whileTo create a while loop
withUsed to simplify exception handling
yieldTo end a function, returns a generator

Exceptions

ExceptionDescription
ArithmeticErrorRaised when an error occurs in numeric calculations
AssertionErrorRaised when an assert statement fails
AttributeErrorRaised when attribute reference or assignment fails
ExceptionBase class for all exceptions
EOFErrorRaised when the input() method hits an "end of file" condition (EOF)
FloatingPointErrorRaised when a floating point calculation fails
GeneratorExitRaised when a generator is closed (with the close() method)
ImportErrorRaised when an imported module does not exist
IndentationErrorRaised when indendation is not correct
IndexErrorRaised when an index of a sequence does not exist
KeyErrorRaised when a key does not exist in a dictionary
KeyboardInterruptRaised when the user presses Ctrl+c, Ctrl+z or Delete
LookupErrorRaised when errors raised cant be found
MemoryErrorRaised when a program runs out of memory
NameErrorRaised when a variable does not exist
NotImplementedErrorRaised when an abstract method requires an inherited class to override the method
OSErrorRaised when a system related operation causes an error
OverflowErrorRaised when the result of a numeric calculation is too large
ReferenceErrorRaised when a weak reference object does not exist
RuntimeErrorRaised when an error occurs that do not belong to any specific expections
StopIterationRaised when the next() method of an iterator has no further values
SyntaxErrorRaised when a syntax error occurs
TabErrorRaised when indentation consists of tabs or spaces
SystemErrorRaised when a system error occurs
SystemExitRaised when the sys.exit() function is called
TypeErrorRaised when two different types are combined
UnboundLocalErrorRaised when a local variable is referenced before assignment
UnicodeErrorRaised when a unicode problem occurs
UnicodeEncodeErrorRaised when a unicode encoding problem occurs
UnicodeDecodeErrorRaised when a unicode decoding problem occurs
UnicodeTranslateErrorRaised when a unicode translation problem occurs
ValueErrorRaised when there is a wrong value in a specified data type
ZeroDivisionErrorRaised when the second operator in a division is zero

Glossary

FeatureDescription
IndentationIndentation refers to the spaces at the beginning of a code line
CommentsComments are code lines that will not be executed
Multi Line CommentsHow to insert comments on multiple lines
Creating VariablesVariables are containers for storing data values
Variable NamesHow to name your variables
Assign Values to Multiple VariablesHow to assign values to multiple variables
Output VariablesUse the print statement to output variables
String ConcatenationHow to combine strings
Global VariablesGlobal variables are variables that belongs to the global scope
Built-In Data TypesPython has a set of built-in data types
Getting Data TypeHow to get the data type of an object
Setting Data TypeHow to set the data type of an object
NumbersThere are three numeric types in Python
IntThe integer number type
FloatThe floating number type
ComplexThe complex number type
Type ConversionHow to convert from one number type to another
Random NumberHow to create a random number
Specify a Variable TypeHow to specify a certain data type for a variable
String LiteralsHow to create string literals
Assigning a String to a VariableHow to assign a string value to a variable
Multiline StringsHow to create a multi line string
Strings are ArraysStrings in Python are arrays of bytes representing Unicode characters
Slicing a StringHow to slice a string
Negative Indexing on a StringHow to use negative indexing when accessing a string
String LengthHow to get the length of a string
Check In StringHow to check if a string contains a specified phrase
Format StringHow to combine two strings
Escape CharactersHow to use escape characters
Boolean ValuesTrue or False
Evaluate BooleansEvaluate a value or statement and return either True or False
Return Boolean ValueFunctions that return a Boolean value
OperatorsUse operator to perform operations in Python
Arithmetic OperatorsArithmetic operator are used to perform common mathematical operations
Assignment OperatorsAssignment operators are use to assign values to variables
Comparison OperatorsComparison operators are used to compare two values
Logical OperatorsLogical operators are used to combine conditional statements
Identity OperatorsIdentity operators are used to see if two objects are in fact the same object
Membership OperatorsMembership operators are used to test is a sequence is present in an object
Bitwise OperatorsBitwise operators are used to compare (binary) numbers
ListsA list is an ordered, and changeable, collection
Access List ItemsHow to access items in a list
Change List ItemHow to change the value of a list item
Loop Through List ItemsHow to loop through the items in a list
List ComprehensionHow use a list comprehensive
Check if List Item ExistsHow to check if a specified item is present in a list
List LengthHow to determine the length of a list
Add List ItemsHow to add items to a list
Remove List ItemsHow to remove list items
Copy a ListHow to copy a list
Join Two ListsHow to join two lists
TupleA tuple is an ordered, and unchangeable, collection
Access Tuple ItemsHow to access items in a tuple
Change Tuple ItemHow to change the value of a tuple item
Loop List ItemsHow to loop through the items in a tuple
Check if Tuple Item ExistsHow to check if a specified item is present in a tuple
Tuple LengthHow to determine the length of a tuple
Tuple With One ItemHow to create a tuple with only one item
Remove Tuple ItemsHow to remove tuple items
Join Two TuplesHow to join two tuples
SetA set is an unordered, and unchangeable, collection
Access Set ItemsHow to access items in a set
Add Set ItemsHow to add items to a set
Loop Set ItemsDETTE KAPITTELET MANGLER
Check if Set Item ExistsDETTE KAPITTELET MANGLER
Set LengthHow to determine the length of a set
Remove Set ItemsHow to remove set items
Join Two SetsHow to join two sets
DictionaryA dictionary is an unordered, and changeable, collection
Access Dictionary ItemsHow to access items in a dictionary
Change Dictionary ItemHow to change the value of a dictionary item
Loop Dictionary ItemsHow to loop through the items in a tuple
Check if Dictionary Item ExistsHow to check if a specified item is present in a dictionary
Dictionary LengthHow to determine the length of a dictionary
Add Dictionary ItemHow to add an item to a dictionary
Remove Dictionary ItemsHow to remove dictionary items
Copy DictionaryHow to copy a dictionary
Nested DictionariesA dictionary within a dictionary
If StatementHow to write an if statement
If IndentationIf statemnts in Python relies on indentation (whitespace at the beginning of a line)
Elifelif is the same as "else if" in other programming languages
ElseHow to write an if...else statement
Shorthand IfHow to write an if statement in one line
Shorthand If ElseHow to write an if...else statement in one line
If ANDUse the and keyword to combine if statements
If ORUse the or keyword to combine if statements
Nested IfHow to write an if statement inside an if statement
The pass Keyword in IfUse the pass keyword inside empty if statements
WhileHow to write a while loop
While BreakHow to break a while loop
While ContinueHow to stop the current iteration and continue wit the next
While ElseHow to use an else statement in a while loop
ForHow to write a for loop
Loop Through a StringHow to loop through a string
For BreakHow to break a for loop
For ContinueHow to stop the current iteration and continue wit the next
Looping Through a rangeeHow to loop through a range of values
For ElseHow to use an else statement in a for loop
Nested LoopsHow to write a loop inside a loop
For passUse the pass keyword inside empty for loops
FunctionHow to create a function in Python
Call a FunctionHow to call a function in Python
Function ArgumentsHow to use arguments in a function
*argsTo deal with an unknown number of arguments in a function, use the * symbol before the parameter name
Keyword ArgumentsHow to use keyword arguments in a function
*kwargsTo deal with an unknown number of keyword arguments in a function, use the * symbol before the parameter name
Default Parameter ValueHow to use a default parameter value
Passing a List as an ArgumentHow to pass a list as an argument
Function Return ValueHow to return a value from a function
The pass Statement i FunctionsUse the pass statement in empty functions
Function RecursionFunctions that can call itself is called recursive functions
Lambda FunctionHow to create anonymous functions in Python
Why Use Lambda FunctionsLearn when to use a lambda function or not
ArrayLists can be used as Arrays
What is an ArrayArrays are variables that can hold more than one value
Access ArraysHow to access array items
Array LengthHow to get the length of an array
Looping Array ElementsHow to loop through array elements
Add Array ElementHow to add elements from an array
Remove Array ElementHow to remove elements from an array
Array MethodsPython has a set of Array/Lists methods
ClassA class is like an object constructor
Create ClassHow to create a class
The Class init() FunctionThe init() function is executed when the class is initiated
Object MethodsMethods in objects are functions that belongs to the object
selfThe self parameter refers to the current instance of the class
Modify Object PropertiesHow to modify properties of an object
Delete Object PropertiesHow to modify properties of an object
Delete ObjectHow to delete an object
Class pass StatementUse the pass statement in empty classes
Create Parent ClassHow to create a parent class
Create Child ClassHow to create a child class
Create the init() FunctionHow to create the init() function
super FunctionThe super() function make the child class inherit the parent class
Add Class PropertiesHow to add a property to a class
Add Class MethodsHow to add a method to a class
IteratorsAn iterator is an object that contains a countable number of values
Iterator vs IterableWhat is the difference between an iterator and an iterable
Loop Through an IteratorHow to loop through the elements of an iterator
Create an IteratorHow to create an iterator
StopIterationHow to stop an iterator
Global ScopeWhen does a variable belong to the global scope?
Global KeywordThe global keyword makes the variable global
Create a ModuleHow to create a module
Variables in ModulesHow to use variables in a module
Renaming a ModuleHow to rename a module
Built-in ModulesHow to import built-in modules
Using the dir() FunctionList all variable names and function names in a module
Import From ModuleHow to import only parts from a module
Datetime ModuleHow to work with dates in Python
Date OutputHow to output a date
Create a Date ObjectHow to create a date object
The strftime MethodHow to format a date object into a readable string
Date Format CodesThe datetime module has a set of legal format codes
JSONHow to work with JSON in Python
Parse JSONHow to parse JSON code in Python
Convert into JSONHow to convert a Python object in to JSON
Format JSONHow to format JSON output with indentations and line breaks
Sort JSONHow to sort JSON
RegEx ModuleHow to import the regex module
RegEx FunctionsThe re module has a set of functions
Metacharacters in RegExMetacharacters are characters with a special meaning
RegEx Special SequencesA backslash followed by a a character has a special meaning
RegEx SetsA set is a set of characters inside a pair of square brackets with a special meaning
RegEx Match ObjectThe Match Object is an object containing information about the search and the result
Install PIPHow to install PIP
PIP PackagesHow to download and install a package with PIP
PIP Remove PackageHow to remove a package with PIP
Error HandlingHow to handle errors in Python
Handle Many ExceptionsHow to handle more than one exception
Try ElseHow to use the else keyword in a try statement
Try FinallyHow to use the finally keyword in a try statement
raiseHow to raise an exception in Python

W3 School Python module reference with descriptions

Random module

MethodDescription
seed()Initialize the random number generator
getstate()Returns the current internal state of the random number generator
setstate()Restores the internal state of the random number generator
getrandbits()Returns a number representing the random bits
randrange()Returns a random number between the given range
randint()Returns a random number between the given range
choice()Returns a random element from the given sequence
choices()Returns a list with a random selection from the given sequence
shuffle()Takes a sequence and returns the sequence in a random order
sample()Returns a given sample of a sequence
random()Returns a random float number between 0 and 1
uniform()Returns a random float number between two given parameters
triangular()Returns a random float number between two given parameters, you can also set a mode parameter to specify the midpoint between the two other parameters
betavariate()Returns a random float number between 0 and 1 based on the Beta distribution (used in statistics)
expovariate()Returns a random float number based on the Exponential distribution (used in statistics)
gammavariate()Returns a random float number based on the Gamma distribution (used in statistics)
gauss()Returns a random float number based on the Gaussian distribution (used in probability theories)
lognormvariate()Returns a random float number based on a log-normal distribution (used in probability theories)
normalvariate()Returns a random float number based on the normal distribution (used in probability theories)
vonmisesvariate()Returns a random float number based on the von Mises distribution (used in directional statistics)
paretovariate()Returns a random float number based on the Pareto distribution (used in probability theories)
weibullvariate()Returns a random float number based on the Weibull distribution (used in statistics)

Requests module

MethodDescription
delete(url, args)Sends a DELETE request to the specified url
get(url, params, args)Sends a GET request to the specified url
head(url, args)Sends a HEAD request to the specified url
patch(url, data, args)Sends a PATCH request to the specified url
post(url, data, json, args)Sends a POST request to the specified url
put(url, data, args)Sends a PUT request to the specified url
request(method, url, args)Sends a request of the specified method to the specified url

Statistics module

MethodDescription
statistics.harmonic_mean()Calculates the harmonic mean (central location) of the given data
statistics.mean()Calculates the mean (average) of the given data
statistics.median()Calculates the median (middle value) of the given data
statistics.median_grouped()Calculates the median of grouped continuous data
statistics.median_high()Calculates the high median of the given data
statistics.median_low()Calculates the low median of the given data
statistics.mode()Calculates the mode (central tendency) of the given numeric or nominal data
statistics.pstdev()Calculates the standard deviation from an entire population
statistics.stdev()Calculates the standard deviation from a sample of data
statistics.pvariance()Calculates the variance of an entire population
statistics.variance()Calculates the variance from a sample of data

Math module

MethodDescription
math.acos()Returns the arc cosine of a number
math.acosh()Returns the inverse hyperbolic cosine of a number
math.asin()Returns the arc sine of a number
math.asinh()Returns the inverse hyperbolic sine of a number
math.atan()Returns the arc tangent of a number in radians
math.atan2()Returns the arc tangent of y/x in radians
math.atanh()Returns the inverse hyperbolic tangent of a number
math.ceil()Rounds a number up to the nearest integer
math.comb()Returns the number of ways to choose k items from n items without repetition and order
math.copysign()Returns a float consisting of the value of the first parameter and the sign of the second parameter
math.cos()Returns the cosine of a number
math.cosh()Returns the hyperbolic cosine of a number
math.degrees()Converts an angle from radians to degrees
math.dist()Returns the Euclidean distance between two points (p and q), where p and q are the coordinates of that point
math.erf()Returns the error function of a number
math.erfc()Returns the complementary error function of a number
math.exp()Returns E raised to the power of x
math.expm1()Returns Ex - 1
math.fabs()Returns the absolute value of a number
math.factorial()Returns the factorial of a number
math.floor()Rounds a number down to the nearest integer
math.fmod()Returns the remainder of x/y
math.frexp()Returns the mantissa and the exponent, of a specified number
math.fsum()Returns the sum of all items in any iterable (tuples, arrays, lists, etc.)
math.gamma()Returns the gamma function at x
math.gcd()Returns the greatest common divisor of two integers
math.hypot()Returns the Euclidean norm
math.isclose()Checks whether two values are close to each other, or not
math.isfinite()Checks whether a number is finite or not
math.isinf()Checks whether a number is infinite or not
math.isnan()Checks whether a value is NaN (not a number) or not
math.isqrt()Rounds a square root number downwards to the nearest integer
math.ldexp()Returns the inverse of math.frexp() which is x * (2**i) of the given numbers x and i
math.lgamma()Returns the log gamma value of x
math.log()Returns the natural logarithm of a number, or the logarithm of number to base
math.log10()Returns the base-10 logarithm of x
math.log1p()Returns the natural logarithm of 1+x
math.log2()Returns the base-2 logarithm of x
math.perm()Returns the number of ways to choose k items from n items with order and without repetition
math.pow()Returns the value of x to the power of y
math.prod()Returns the product of all the elements in an iterable
math.radians()Converts a degree value into radians
math.remainder()Returns the closest value that can make numerator completely divisible by the denominator
math.sin()Returns the sine of a number
math.sinh()Returns the hyperbolic sine of a number
math.sqrt()Returns the square root of a number
math.tan()Returns the tangent of a number
math.tanh()Returns the hyperbolic tangent of a number
math.trunc()Returns the truncated integer parts of a number
math.eReturns Euler's number (2.7182...)
math.infReturns a floating-point positive infinity
math.nanReturns a floating-point NaN (Not a Number) value
math.piReturns PI (3.1415...)
math.tauReturns tau (6.2831...)

cMath module

MethodDescription
cmath.acos(x)Returns the arc cosine value of x
cmath.acosh(x)Returns the hyperbolic arc cosine of x
cmath.asin(x)Returns the arc sine of x
cmath.asinh(x)Returns the hyperbolic arc sine of x
cmath.atan(x)Returns the arc tangent value of x
cmath.atanh(x)Returns the hyperbolic arctangent value of x
cmath.cos(x)Returns the cosine of x
cmath.cosh(x)Returns the hyperbolic cosine of x
cmath.exp(x)Returns the value of Ex, where E is Euler's number (approximately 2.718281...), and x is the number passed to it
cmath.isclose()Checks whether two values are close, or not
cmath.isfinite(x)Checks whether x is a finite number
cmath.isinf(x)Check whether x is a positive or negative infinty
cmath.isnan(x)Checks whether x is NaN (not a number)
cmath.log(x[, base])Returns the logarithm of x to the base
cmath.log10(x)Returns the base-10 logarithm of x
cmath.phase()Return the phase of a complex number
cmath.polar()Convert a complex number to polar coordinates
cmath.rect()Convert polar coordinates to rectangular form
cmath.sin(x)Returns the sine of x
cmath.sinh(x)Returns the hyperbolic sine of x
cmath.sqrt(x)Returns the square root of x
cmath.tan(x)Returns the tangent of x
cmath.tanh(x)Returns the hyperbolic tangent of x
cmath.eReturns Euler's number (2.7182...)
cmath.infReturns a floating-point positive infinity value
cmath.infjReturns a complex infinity value
cmath.nanReturns floating-point NaN (Not a Number) value
cmath.nanjReturns coplext NaN (Not a Number) value
cmath.piReturns PI (3.1415...)
cmath.tauReturns tau (6.2831...)

Common sequence operations (sequence types: list, tuple, range)

The operations in the following table are supported by most sequence types, both mutable and immutable. The collections.abc.Sequence ABC is provided to make it easier to correctly implement these operations on custom sequence types.

This table lists the sequence operations sorted in ascending priority. In the table, s and t are sequences of the same type, n, i, j and k are integers and x is an arbitrary object that meets any type and value restrictions imposed by s.

The in and not in operations have the same priorities as the comparison operations. The + (concatenation) and * (repetition) operations have the same priority as the corresponding numeric operations.

OperationResultNotes
x in sTrue if an item of s is equal to x, else False(1)
x not in sFalse if an item of s is equal to x, else True(1)
s + tthe concatenation of s and t(6)(7)
s * n or n * sequivalent to adding s to itself n times(2)(7)
s[i]ith item of s, origin 0(3)
s[i:j]slice of s from i to j(3)(4)
s[i:j:k]slice of s from i to j with step k(3)(5))
len(s)length of s
min(s)smallest item of s
max(s)largest item of s
s.index(x[, i[, j]])index of the first occurrence of x in s (at or after index i and before index j)(8)
s.count(x)total number of occurrences of x in s

Sequences of the same type 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 Comparisons in the language reference.)

Notes:

1. While the in and not in operations are used only for simple containment testing in the general case, some specialised sequences (such as str, bytes and bytearray) also use them for subsequence testing:

>>> "gg" in "eggs"
True

2. Values of n less than 0 are treated as 0 (which yields an empty sequence of the same type as s). Note that items in the sequence s are not copied; they are referenced multiple times. This often haunts new Python programmers; consider:

>>> lists = [[]] * 3
>>> lists
[[], [], []]
>>> lists[0].append(3)
>>> lists
[[3], [3], [3]]

What has happened is that [[]] is a one-element list containing an empty list, so all three elements of [[]] * 3 are references to this single empty list. Modifying any of the elements of lists modifies this single list. You can create a list of different lists this way:

>>> lists = [[] for i in range(3)]
>>> lists[0].append(3)
>>> lists[1].append(5)
>>> lists[2].append(7)
>>> lists
[[3], [5], [7]]

Further explanation is available in the FAQ entry How do I create a multidimensional list?.

3. If i or j is negative, the index is relative to the end of sequence s: len(s) + i or len(s) + j is substituted. But note that -0 is still 0.

4. The slice of s from i to j is defined as the sequence of items with index k such that i <= k < j. If i or j is greater than len(s), use len(s). If i is omitted or None, use 0. If j is omitted or None, use len(s). If i is greater than or equal to j, the slice is empty.

5. The slice of s from i to j with step k is defined as the sequence of items with index x = i + n*k such that 0 <= n < (j-i)/k. In other words, the indices are i, i+k, i+2*k, i+3*k and so on, stopping when j is reached (but never including j). When k is positive, i and j are reduced to len(s) if they are greater. When k is negative, i and j are reduced to len(s) - 1 if they are greater. If i or j are omitted or None, they become "end" values (which end depends on the sign of k). Note, k cannot be zero. If k is None, it is treated like 1.

6. Concatenating immutable sequences always results in a new object. This means that building up a sequence by repeated concatenation will have a quadratic runtime cost in the total sequence length. To get a linear runtime cost, you must switch to one of the alternatives below:

  • if concatenating str objects, you can build a list and use str.join() at the end or else write to an io.StringIO instance and retrieve its value when complete
  • if concatenating bytes objects, you can similarly use bytes.join() or io.BytesIO, or you can do in-place concatenation with a bytearray object. bytearray objects are mutable and have an efficient overallocation mechanism
  • if concatenating tuple objects, extend a list instead
  • for other types, investigate the relevant class documentation

7. Some sequence types (such as range) only support item sequences that follow specific patterns, and hence don't support sequence concatenation or repetition.

8. index raises ValueError when x is not found in s. Not all implementations support passing the additional arguments i and j. These arguments allow efficient searching of subsections of the sequence. Passing the extra arguments is roughly equivalent to using s[i:j].index(x), only without copying any data and with the returned index being relative to the start of the sequence rather than the start of the slice.

Mutable sequence types (operations such as slicing, insert, etc.)

The operations in the following table are defined on mutable sequence types. The collections.abc.MutableSequence ABC is provided to make it easier to correctly implement these operations on custom sequence types.

In the table s is an instance of a mutable sequence type, t is any iterable object and x is an arbitrary object that meets any type and value restrictions imposed by s (for example, bytearray only accepts integers that meet the value restriction 0 <= x <= 255).

OperationResultNotes
s[i] = xitem i of s is replaced by x
s[i:j] = tslice of s from i to j is replaced by the contents of the iterable t
del s[i:j]same as s[i:j] = []
s[i:j:k] = tthe elements of s[i:j:k] are replaced by those of t(1)
del s[i:j:k]removes the elements of s[i:j:k] from the list
s.append(x)appends x to the end of the sequence (same as s[len(s):len(s)] = [x])
s.clear()removes all items from s (same as del s[:])(5)
s.copy()creates a shallow copy of s (same as s[:])(5)
s.extend(t) or s += textends s with the contents of t (for the most part the same as s[len(s):len(s)] = t)
s *= nupdates s with its contents repeated n times(6)
s.insert(i, x)inserts x into s at the index given by i (same as s[i:i] = [x])
s.pop([i])retrieves the item at i and also removes it from s(2)
s.remove(x)remove the first item from s where s[i] is equal to x(3)
s.reverse()reverses the items of s in place(4)

1. t must have the same length as the slice it is replacing.

2. The optional argument i defaults to -1, so that by default the last item is removed and returned.

3. remove() raises ValueError when x is not found in s.

4. The reverse() method modifies the sequence in place for economy of space when reversing a large sequence. To remind users that it operates by side effect, it does not return the reversed sequence.

5. clear() and copy() are included for consistency with the interfaces of mutable containers that don't support slicing operations (such as dict and set). copy() is not part of the collections.abc.MutableSequence ABC, but most concrete mutable sequence classes provide it.

6. The value n is an integer, or an object implementing __index__(). Zero and negative values of n clear the sequence. Items in the sequence are not copied; they are referenced multiple times, as explained for s * n under Common Sequence Operations.

Docs and Examples

Built-in Functions

abs(x)

Description: The abs() function returns the absolute value of the given number. If the number is a complex number, then abs() returns its magnitude.

Syntax: The syntax of abs() method is: abs(num).

Paramaters: abs() method takes a single argument, num: a number whose absolute value is to be returned. The number can be:

  • integer
  • floating number
  • complex number

Return value: abs() method returns the absolute value of the given number.

  • For integers - integer absolute value is returned
  • For floating numbers - floating absolute value is returned
  • For complex numbers - magnitude of the number is returned

Examples:

Ex 0: Documentation

Return the absolute value of a number. The argument may be an integer, a floating point number, or an object implementing __abs__(). If the argument is a complex number, its magnitude is returned.


Ex 1: Getting absolute value of an integer and a floating number
# random integer
integer = -20
print('Absolute value of -20 is:', abs(integer))

#random floating number
floating = -30.33
print('Absolute value of -30.33 is:', abs(floating))

Output:

Absolute value of -20 is: 20
Absolute value of -30.33 is: 30.33

Ex 2: Getting magnitude of a complex number
# random complex number
complex = (3 - 4j)
print('Magnitude of 3 - 4j is:', abs(complex))

Output:

Magnitude of 3 - 4j is: 5.0

Ex 3: Example using abs on an int, float, and complex number, respectively
a = -2
b = -3.4
c = complex(-3,-4)

print(abs(a)) # 2
print(abs(b)) # 3.4
print(abs(c)) # 5.0 (comes from: sqrt((-3)^2 + (-4)^2))

As can be seen above, abs returns an int when it receives a whole number and a float otherwise.



aiter(async_iterable)

Return an asynchronous iterator for an asynchronous iterable. Equivalent to calling x.__aiter__().

aiter(x) itself has an __aiter__() method that returns x, so aiter(aiter(x)) is the same as aiter(x).

Note: Unlike iter(), aiter() has no 2-argument variant.

New in version 3.10.


all(iterable)

Description: The all() function returns True if all elements in the given iterable are true (or if the iterable is empty). If not, it returns False.

Syntax: The syntax of the all() function is: all(iterable).

Parameters: The all() function takes a single parameter, iterable: any iterable (list, tuple, dictionary, etc.) which contains elements.

Return value: The all() function returns:

  • True - If all elements in an iterable are true (or if the iterable is empty)
  • False - If any element in an iterable is false

Falsy values in Python: Recall that all values in Python are considered truthy except for the following which are falsy (more can be found in the docs on truth value testing):

  • None
  • False
  • 0
  • 0.0
  • 0j
  • Decimal(0)
  • Fraction(0, 1)
  • [] - an empty list
  • {} - an empty dict
  • () - an empty tuple
  • '' - an empty str
  • b'' - an empty bytes
  • set() - an empty set
  • an empty range, like range(0)
  • objects for which
    • obj.__bool__() returns False
    • obj.__len__() returns 0

Examples:

Ex 0: Documentation

Return True if all elements of the iterable are true (or if the iterable is empty). Equivalent to:

def all(iterable):
for element in iterable:
if not element:
return False
return True

Ex 1: Lists (works in a similar way for tuples and sets)
# all values true
l = [1, 3, 4, 5]
print(all(l)) # True

# all values false
l = [0, False]
print(all(l)) # False

# one false value
l = [1, 3, 4, 0]
print(all(l)) # False

# one true value
l = [0, False, 5]
print(all(l)) # False

# empty iterable
l = []
print(all(l)) # True

Ex 2: Strings
s = "This is good"
print(all(s)) # True

# 0 is False
# '0' is True
s = '000'
print(all(s)) # True

s = ''
print(all(s)) # True

Some things to note about two of the code examples above:

  • "This is good": This is true because all values (i.e., characters) in the iterable "This is good" are truthy; in particular, the spaces ' ' have an ordinal value of 32 (i.e., ord(' ') returns 32).

  • '': This is true because the iterable '' is empty. Hence, when the functional equivalent of all()

    def all(iterable):
    for element in iterable:
    if not element:
    return False
    return True

    is executed, the for loop never runs and True is quickly returned.


Ex 3: Dictionaries (return True if all keys, not values, are true or the dictionary is empty; else return False)
s = {0: 'False', 1: 'False'}
print(all(s)) # False

s = {1: 'True', 2: 'True'}
print(all(s)) # True

s = {1: 'True', False: 0}
print(all(s)) # False

s = {}
print(all(s)) # True

# 0 is False
# '0' is True
s = {'0': 'True'}
print(all(s)) # True


anext(async_iterator[, default])

When awaited, return the next item from the given asynchronous iterator, or default if given and the iterator is exhausted.

This is the async variant of the next() builtin, and behaves similarly.

This calls the __anext__() method of async_iterator, returning an awaitable. Awaiting this returns the next value of the iterator. If default is given, it is returned if the iterator is exhausted, otherwise StopAsyncIteration is raised.

New in version 3.10.


any(iterable)

Description: The any() function returns True if any element of the given iterable is True. If not (or if the iterable is empty), it returns False.

Syntax: The syntax of the any() function is: any(iterable).

Parameters: The any() function takes a single parameter, iterable: any iterable (list, tuple, dictionary, etc.) which contains elements.

Return value: The any() function returns:

  • True - If at least one element of an iterable is true
  • False - If all elements are false or if an iterable is empty

Falsy values in Python: Recall that all values in Python are considered truthy except for the following which are falsy (more can be found in the docs on truth value testing):

  • None
  • False
  • 0
  • 0.0
  • 0j
  • Decimal(0)
  • Fraction(0, 1)
  • [] - an empty list
  • {} - an empty dict
  • () - an empty tuple
  • '' - an empty str
  • b'' - an empty bytes
  • set() - an empty set
  • an empty range, like range(0)
  • objects for which
    • obj.__bool__() returns False
    • obj.__len__() returns 0

Examples:

Ex 0: Documentation

Return True if any element of the iterable is true. If the iterable is empty, return False. Equivalent to:

def any(iterable):
for element in iterable:
if element:
return True
return False

Ex 1: Lists (works in a similar way for tuples and sets)
# all true except 0
l = [1, 3, 4, 0]
print(any(l)) # True

# both false
l = [0, False]
print(any(l)) # False

# all false except 5
l = [0, False, 5]
print(any(l)) # True

# empty
l = []
print(any(l)) # False

Ex 2: Strings
# all elements are true
s = "This is good"
print(any(s)) # True

# all elements are true
s = '000'
print(any(s)) # True

# false (empty iterable)
s = ''
print(any(s)) # False

Ex 3: Dictionaries (return False if all keys, not values, are false, or the dictionary is empty; else return True)
# 0 is False
d = {0: 'False'}
print(any(d)) # False

# 1 is True
d = {0: 'False', 1: 'True'}
print(any(d)) # True

# 0 and False are false
d = {0: 'False', False: 0}
print(any(d)) # False

# iterable is empty
d = {}
print(any(d)) # False

# 0 is False
# '0' is True
d = {'0': 'False'}
print(any(d)) # True


ascii(object)

Description: The ascii() method returns a string containing a printable representation of an object. It escapes the non-ASCII characters in the string using \x, \u or \U escapes.

Syntax: The syntax of ascii() is: ascii(object)

Parameters: The ascii() method takes an object (like: strings, list etc).

Return value: It returns a string containing a printable representation of an object. For example, ö is changed to \xf6n, is changed to \u221a. The non-ASCII characters in the string are escaped using \x, \u or \U.

Examples:

Ex 0: Documentation

As repr(), return a string containing a printable representation of an object, but escape the non-ASCII characters in the string returned by repr() using \x, \u or \U escapes. This generates a string similar to that returned by repr() in Python 2.


Ex 1: Basic usage (encoding and decoding simple strings)
normalText = 'Python is interesting'
print(ascii(normalText))

otherText = 'Pythön is interesting'
print(ascii(otherText))

print('Pyth\xf6n is interesting')

Output:

'Python is interesting'
'Pyth\xf6n is interesting'
Pythön is interesting

Ex 2: Applying ascii() to each element of a list
randomList = ['Python', 'Pythön', 5]
print(ascii(randomList))

Output:

['Python', 'Pyth\xf6n', 5]


bin(x)

Description: The bin() method converts and returns the binary equivalent string of a given integer. If the parameter isn't an integer, it has to implement __index__() method to return an integer.

Syntax: The syntax of bin() method is: bin(num)

Parameters: The bin() method takes a single parameter num: an integer number whose binary equivalent is to be calculated. If not an integer, should implement __index__() method to return an integer.

Return value: bin() method returns the binary string equivalent to the given integer. If not specified an integer, it raises a TypeError exception highlighting the type cannot be interpreted as an integer.

Examples:

Ex 0: Documentation

Convert an integer number to a binary string prefixed with 0b.

The result is a valid Python expression. If x is not a Python int object, it has to define an __index__() method that returns an integer.

>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'

If prefix 0b is desired or not, you can use either of the following ways:

>>> format(14, '#b'), format(14, 'b')
('0b1110', '1110')
>>> f'{14:#b}', f'{14:b}'
('0b1110', '1110')

See also format() for more information.


Ex 1: Converting an integer to binary using bin()
number = 5
print('The binary equivalent of 5 is:', bin(number))

Output:

The binary equivalent of 5 is: 0b101

The prefix 0b represents that the result is a binary string.


Ex 2: Convert an object to binary implementing __index__() method
class Quantity:
apple = 1
orange = 2
grapes = 2

def __index__(self):
return self.apple + self.orange + self.grapes

print('The binary equivalent of quantity is:', bin(Quantity()))

Output:

The binary equivalent of quantity is: 0b101

Here, we've sent an object of class Quantity to the bin() method. The bin() method doesn't raise an error even if the object Quantity is not an integer. This is because we have implemented the __index__() method which returns an integer (sum of fruit quantities). This integer is then supplied to the bin() method.


Ex 3: Multiple one-line examples
print(bin(4))             # 0b100
print(format(4,'#b')) # 0b100
print(f'{4:#b}') # 0b100
print(format(4,'b')) # 100
print(f'{4:b}') # 100
print(int('100', 2)) # 4
print(int('0b100', 2)) # 4


bool([x])

Description: The bool() function converts a value to Boolean (True or False) using the standard truth testing procedure.

Syntax: The syntax of bool() is: bool([value])

Parameters: It's not mandatory to pass a value to bool(). If you do not pass a value, bool() returns False. In general use, bool() takes a single parameter value.

Return value: bool() returns

  • False if the value is omitted or false
  • True if the value is true

Falsy values in Python: Recall that all values in Python are considered truthy except for the following which are falsy (more can be found in the docs on truth value testing):

  • None
  • False
  • 0
  • 0.0
  • 0j
  • Decimal(0)
  • Fraction(0, 1)
  • [] - an empty list
  • {} - an empty dict
  • () - an empty tuple
  • '' - an empty str
  • b'' - an empty bytes
  • set() - an empty set
  • an empty range, like range(0)
  • objects for which
    • obj.__bool__() returns False
    • obj.__len__() returns 0

Examples:

Ex 0: Documentation

Return a Boolean value (i.e., one of True or False). If x is false or omitted, this (i.e., bool() or bool(x) where x is false) returns False; otherwise it returns True.

x is converted using the standard truth testing procedure. The bool class is a subclass of int (see Numeric Types — int, float, complex). It cannot be subclassed further. Its only instances are False and True (see Boolean Values).


Ex 1: Basic usage on a variety of inputs
test = []
print(test,'is',bool(test))

test = [0]
print(test,'is',bool(test))

test = 0.0
print(test,'is',bool(test))

test = None
print(test,'is',bool(test))

test = True
print(test,'is',bool(test))

test = 'Easy string'
print(test,'is',bool(test))

Output:

[] is False
[0] is True
0.0 is False
None is False
True is True
Easy string is True

Changed in version 3.7: x is now a positional-only parameter.


breakpoint(*args, **kws)

Description: See documentation below. The primary purpose is to be able to drop into the debugger at the call site without the overhead of having to import the pdb module.

Examples:

Ex 0: Documentation

This function drops you into the debugger at the call site.

Specifically, it calls sys.breakpointhook(), passing args and kws straight through. By default, sys.breakpointhook() calls pdb.set_trace() expecting no arguments. In this case, it is purely a convenience function so you don't have to explicitly import pdb or type as much code to enter the debugger. However, sys.breakpointhook() can be set to some other function and breakpoint() will automatically call that, allowing you to drop into the debugger of choice.

Raises an auditing event builtins.breakpoint with argument breakpointhook.

New in version 3.7.


Ex 1: Basic usage of breakpoint

Consider the following somewhat verbose silly example (note how breakpoint would allow us to avoid the usage of pdb below):

import pdb

def add(num1, num2):
# code tries to run until it hits the set_trace for pdb below
pdb.set_trace()
# within the debugger, we can test out what is going on thus far
# for example, entering num1 will tell us what num1 is at this point (same for num2)
# pdb really has a ton of helpful things; for example,
# simply typing 'help' shows documented commands you can use within the interactive debugger
# if you see a command you're not sure about, then simply type 'help <command>'
# we can type 'step' to step through our code
# right now typing 'some_var' within pdb would give us a NameError since we have not reached that line yet
# we can run 'continue' to continue through the code until we hit a return
# the 'a' command is also helpful since it will give you the arguments of the function you're in at that point in execution
# you can interactively change the value of different arguments to test things out
# the 'w' command will give you context for debugging
# finally 'exit' will let you exit the debugger
some_var = 4 * 5
print(some_var)
return num1 + num2

add(4, 'string')

We can certainly use pdb, the Python debugging module in the standard library, as illustrated above, but it can be rather cumbersome to import a module just to do some debugging. For the sake of convenience, you can get everything above by simply removing the import pdb statement as well as changing the line pdb.set_trace() to breakpoint(). We then end up with the exact some functionality but avoid importing a module:

def add(num1, num2):
breakpoint()
some_var = 4 * 5
print(some_var)
return num1 + num2

add(4, 'string')


NOTE: Some notes about str, byte, bytearray, and Unicode strings

The following notes largely come from [3] in a variety of places.

Overview: The normal str string object is an immutable (unchangeable) sequence of characters accessed by offset (position). Its characters are code point ordinals in the underlying character set, and individual characters are string objects of length 1.

The full string object model varies across lines.

Python 3.X has three string types with similar interfaces:

  • str: An immutable sequence of characters, used for all text—-both ASCII and richer Unicode.
  • bytes: An immutable sequence of short integers, used for the byte values of binary data.
  • bytearray: A mutable variant of bytes.

The following literal forms and calls make specialized strings:

  • b'...': bytes string literal in Python 3.X: sequence of 8-bit byte values representing raw binary data.
  • bytearray(...): bytearray string construction: a mutable variant of bytes.
  • str(), bytes(), bytearray(): Create strings from objects, with possible Unicode encoding/decoding in Python 3.X.

byte and bytearray methods: Python 3.X bytes and bytearray string types have method sets similar to that of the normal str type, but do not overlap exactly due to differing roles. (str is Unicode text, bytes is raw binary data, and bytearray is mutable.) In the following, run in Python 3.9, set(dir(X)) – set(dir(Y)) computes attributes unique to X:

>>> set(dir(str)) - set(dir(bytes))
{
'isidentifier', 'encode', 'isnumeric',
'format', 'format_map', 'isdecimal',
'isprintable', 'casefold'
}

>>> set(dir(bytes)) - set(dir(str))
{
'fromhex', 'decode', 'hex'
}

>>> set(dir(bytearray)) - set(dir(bytes))
{
'clear', '__setitem__', '__iadd__',
'reverse', 'pop', 'insert',
'__delitem__', 'append', '__imul__',
'__alloc__', 'remove', 'extend',
'copy'
}

Of note:

  • str does not support Unicode decoding (it is already decoded text), but may be encoded to bytes.
  • bytes and bytearray do not support Unicode encoding (they are raw bytes, including both media and already encoded text), but may be decoded to str.
  • bytes and bytearray do not support string formatting (implemented by str.format).
  • bytearray has extra mutable in-place methods and operators similar to list (e.g., append, +=).

Unicode strings: All text is Unicode text, including text encoded with one character per byte (8 bits) in the ASCII scheme. Python supports richer character sets and encoding schemes with Unicode--strings which may use multiple bytes to represent characters in memory, and which translate text to and from various encodings on files. This support differs in Python lines. Python 3.X treats all text as Unicode and represents binary data separately, while Python 2.X distinguishes 8-bit text (and data) from possibly wider Unicode text.

In Python 3.X, the normal str type and 'ccc' literal represents all text, both 8-bit and richer Unicode. str is an immutable sequence of characters-—decoded Unicode code points (ordinal identifiers) in memory.

A separate bytes type and b'ccc' literal represents binary data byte values, including media and encoded Unicode text. bytes is an immutable sequence of small integers (8-bit byte values), but supports most str operations, and prints content as ASCII characters when possible. An additional bytearray type is a mutable variant of bytes, with extra list-like methods for in-place changes.

Also in 3.X, normal files created by open() imply str and bytes objects for content in text and binary mode, respectively. In text mode, files automatically encode on output and decode on input.

Unicode support in Python 3.X: Python 3.X allows non-ASCII characters to be coded in strings with hex (\x) and both 16- and 32-bit Unicode (\u, \U) escapes. In addition, chr() supports Unicode character codes:

>>> 'A\xE4B'
'AäB'

>>> 'A\u00E4B'
'AäB'

>>> 'A\U000000E4B'
'AäB'

>>> chr(0xe4)
'ä'

byte and bytearray strings: Python 3.X bytes and bytearray string objects represent 8-bit binary data (including encoded Unicode text); are printed as ASCII text when possible; and support most normal str string operations including methods and sequence operations (but not string formatting). For example, the code block

B = b'spam'
print(B)

B = bytes('spam', 'utf-8')
print(B)

print(B[0])
print(ord('s'))

print(B + b'abc')
print(B.split(b'a'))

print(list(B))
print([ chr(c) for c in B ])

print([ ord(c) for c in 'spam' ])
print([ c for c in 'spam' ])

yields the following output (newlines for clarity):

b'spam'
b'spam'

115
115

b'spamabc'
[b'sp', b'm']

[115, 112, 97, 109]
['s', 'p', 'a', 'm']

[115, 112, 97, 109]
['s', 'p', 'a', 'm']

bytearray additionally supports list-like mutable operations:

BA = bytearray(b'spam')
print(BA)
print(BA[0])
print(BA + b'abc')

BA[0] = 116 # Mutability
BA.append(115) # List methods
print(BA)

yields:

bytearray(b'spam')
115
bytearray(b'spamabc')

bytearray(b'tpams')

bytearray([source[, encoding[, errors]]])

Description: The bytearray() method returns a bytearray object which is an array of the given bytes.

prime_numbers = [2, 3, 5, 7]

# convert list to bytearray
byte_array = bytearray(prime_numbers)
print(byte_array)

# Output: bytearray(b'\x02\x03\x05\x07')

Syntax: The syntax of bytearray() method is: bytearray([source[, encoding[, errors]]]). The bytearray() method returns a bytearray object (i.e., array of bytes) which is a mutable sequence of integers in the range 0 <= x < 256. If you want an immutable version, then use the bytes() method.

Parameters: bytearray() takes three optional parameters:

  • source (Optional) - source to initialize the array of bytes.
  • encoding (Optional) - if the source is a string, the encoding of the string.
  • errors (Optional) - if the source is a string, the action to take when the encoding conversion fails

The source parameter can be used to initialize the byte array in the following ways:

TypeDescription
StringConverts the string to bytes using str.encode(). Must also provide encoding and optionally errors
IntegerCreates an array of provided size, all initialized to null
ObjectA read-only buffer of the object will be used to initialize the byte array
IterableCreates an array of size equal to the iterable count and initialized to the iterable elements. Must be iterable of integers between 0 <= x < 256
No source (arguments)Creates an array of size 0.

Return value: The bytearray() method returns an array of bytes of the given size and initialization values.

Examples:

Ex 0: Documentation

Return a new array of bytes.

The bytearray class is a mutable sequence of integers in the range 0 <= x < 256. It has most of the usual methods of mutable sequences, described in Mutable Sequence Types, as well as most methods that the bytes type has, see Bytes and Bytearray Operations.

The optional source parameter can be used to initialize the array in a few different ways:

  • If it is a string, you must also give the encoding (and optionally, errors) parameters; bytearray() then converts the string to bytes using str.encode().
  • If it is an integer, the array will have that size and will be initialized with null bytes.
  • If it is an object conforming to the buffer interface, a read-only buffer of the object will be used to initialize the bytes array.
  • If it is an iterable, it must be an iterable of integers in the range 0 <= x < 256, which are used as the initial contents of the array.

Without an argument, an array of size 0 is created.

See also Binary Sequence Types — bytes, bytearray, memoryview and Bytearray Objects.


Ex 1: Array of bytes from a string
string = "Python is interesting."

# string with encoding 'utf-8'
arr = bytearray(string, 'utf-8')
print(arr)

Output:

bytearray(b'Python is interesting.')

Ex 2: Array of bytes of given integer size
size = 5

arr = bytearray(size)
print(arr)

Output:

bytearray(b'\x00\x00\x00\x00\x00')

Ex 3: Array of bytes from an iterable list
rList = [1, 2, 3, 4, 5]

arr = bytearray(rList)
print(arr)

Output:

bytearray(b'\x01\x02\x03\x04\x05')


bytes([source[, encoding[, errors]]])

Description: The bytes() method returns an immutable bytes object initialized with the given size and data.

message = 'Python is fun'

# convert string to bytes
byte_message = bytes(message, 'utf-8')
print(byte_message)

# Output: b'Python is fun'

Syntax: The syntax of bytes() method is

bytes([source[, encoding[, errors]]])

bytes() method returns a bytes object which is an immutable (cannot be modified) sequence of integers in the range 0 <=x < 256. If you want to use the mutable version, use the bytearray() method.

Parameters: bytes() takes three optional parameters:

  • source (Optional) - source to initialize the array of bytes.
  • encoding (Optional) - if the source is a string, the encoding of the string.
  • errors (Optional) - if the source is a string, the action to take when the encoding conversion fails

The source parameter can be used to initialize the byte array in the following ways:

TypeDescription
StringConverts the string to bytes using str.encode(). Must also provide encoding and optionally errors
IntegerCreates an array of provided size, all initialized to null
ObjectA read-only buffer of the object will be used to initialize the byte array
IterableCreates an array of size equal to the iterable count and initialized to the iterable elements. Must be iterable of integers between 0 <= x < 256
No source (arguments)Creates an array of size 0.

Return value: The bytes() method returns a bytes object of the given size and initialization values.

Return value:

Examples:

Ex 0: Documentation

Return a new "bytes" object, which is an immutable sequence of integers in the range 0 <= x < 256. bytes is an immutable version of bytearray – it has the same non-mutating methods and the same indexing and slicing behavior.

Accordingly, constructor arguments are interpreted as for bytearray().

Bytes objects can also be created with literals, see String and Bytes literals.

See also Binary Sequence Types — bytes, bytearray, memoryview, Bytes Objects, and Bytes and Bytearray Operations.


Ex 1: Convert string to bytes
string = "Python is interesting."

# string with encoding 'utf-8'
arr = bytes(string, 'utf-8')
print(arr)

Output:

b'Python is interesting.'

Ex 2: Create a byte of given integer size
size = 5

arr = bytes(size)
print(arr)

Output:

b'\x00\x00\x00\x00\x00'

Ex 3: Convert iterable list to bytes
rList = [1, 2, 3, 4, 5]

arr = bytes(rList)
print(arr)

Output:

b'\x01\x02\x03\x04\x05'


callable(object)

Description: The callable() method returns True if the object passed appears callable. If not, it returns False.

Syntax: The syntax of callable() is: callable(object)

Parameters: callable() method takes a single argument: object

Return value: The callable() method returns:

  • True - if the object appears callable
  • False - if the object is not callable.

It important to remember that, even if callable() is True, call to the object may still fail.

However, if callable() returns False, call to the object will certainly fail.

Examples:

Ex 0: Documentation

Return True if the object argument appears callable, False if not.

If this returns True, it is still possible that a call fails, but if it is False, calling object will never succeed. Note that classes are callable (calling a class returns a new instance); instances are callable if their class has a __call__() method.

New in version 3.2: This function was first removed in Python 3.0 and then brought back in Python 3.2.


Ex 1: How callable() works
x = 5
print(callable(x))

def testFunction():
print("Test")

y = testFunction
print(callable(y))

Output:

False
True

Here, the object x is not callable. And, the object y appears to be callable (but may not be callable).


Ex 2: Callable object
class Foo:
def __call__(self):
print('Print Something')

print(callable(Foo))

Output:

True

The instance of Foo class appears to be callable (and is callable in this case).

class Foo:
def __call__(self):
print('Print Something')

InstanceOfFoo = Foo()

# Prints 'Print Something'
InstanceOfFoo()

Ex 3: Object appears to be callable but is not callable
class Foo:
def printLine(self):
print('Print Something')

print(callable(Foo))

Output:

True

The instance of Foo class appears to be callable but it's not callable. The following code will raise an error.

class Foo:
def printLine(self):
print('Print Something')

print(callable(Foo))

InstanceOfFoo = Foo()
# Raises an Error
# 'Foo' object is not callable
InstanceOfFoo()

Output:

True
Traceback (most recent call last):
File "", line 10, in
TypeError: 'Foo' object is not callable


chr(i)

Description: The chr() method returns a character (a string) from an integer (represents unicode code point of the character).

Syntax: The syntax of chr() is: chr(i)

Parameters: The chr() method takes a single parameter, an integer i. The valid range of the integer is from 0 through 1,114,111.

Return value: chr() returns a character (a string) whose Unicode code point is the integer i. If the integer i is outside the range, ValueError will be raised.

Examples:

Ex 0: Documentation

Returns a one-character string whose Unicode code point is the integer i.

For example, chr(97) returns the string 'a', while chr(8364) returns the string '€'. This is the inverse of ord().

The valid range for the argument is from 0 through 1,114,111 (0x10FFFF in base 16). ValueError will be raised if i is outside that range.


Ex 1: How chr() works
print(chr(97))
print(chr(65))
print(chr(1200)

Output:

a
A
Ұ

Ex 2: Integer passed to chr() is out of the range
print(chr(-1))

Output:

Traceback (most recent call last):
File "", line 1, in
ValueError: chr() arg not in range(0x110000)

When you run the program, ValueError is raised. It's because the argument passed to chr() method is out of the range.


ASCII Table
DecHexOctBinaryHTMLCharDescription
00000000000000&#0;NULNull
10100100000001&#1;SOHStart of Header
20200200000010&#2;STXStart of Text
30300300000011&#3;ETXEnd of Text
40400400000100&#4;EOTEnd of Transmission
50500500000101&#5;ENQEnquiry
60600600000110&#6;ACKAcknowledge
70700700000111&#7;BELBell
80801000001000&#8;BSBackspace
90901100001001&#9;HTHorizontal Tab
100A01200001010&#10;LFLine Feed
110B01300001011&#11;VTVertical Tab
120C01400001100&#12;FFForm Feed
130D01500001101&#13;CRCarriage Return
140E01600001110&#14;SOShift Out
150F01700001111&#15;SIShift In
161002000010000&#16;DLEData Link Escape
171102100010001&#17;DC1Device Control 1
181202200010010&#18;DC2Device Control 2
191302300010011&#19;DC3Device Control 3
201402400010100&#20;DC4Device Control 4
211502500010101&#21;NAKNegative Acknowledge
221602600010110&#22;SYNSynchronize
231702700010111&#23;ETBEnd of Transmission Block
241803000011000&#24;CANCancel
251903100011001&#25;EMEnd of Medium
261A03200011010&#26;SUBSubstitute
271B03300011011&#27;ESCEscape
281C03400011100&#28;FSFile Separator
291D03500011101&#29;GSGroup Separator
301E03600011110&#30;RSRecord Separator
311F03700011111&#31;USUnit Separator
322004000100000&#32;spaceSpace
332104100100001&#33;!exclamation mark
342204200100010&#34;"double quote
352304300100011&#35;#number
362404400100100&#36;$dollar
372504500100101&#37;%percent
382604600100110&#38;&ampersand
392704700100111&#39;'single quote
402805000101000&#40;(left parenthesis
412905100101001&#41;)right parenthesis
422A05200101010&#42;*asterisk
432B05300101011&#43;+plus
442C05400101100&#44;,comma
452D05500101101&#45;-minus
462E05600101110&#46;.period
472F05700101111&#47;/slash
483006000110000&#48;0zero
493106100110001&#49;1one
503206200110010&#50;2two
513306300110011&#51;3three
523406400110100&#52;4four
533506500110101&#53;5five
543606600110110&#54;6six
553706700110111&#55;7seven
563807000111000&#56;8eight
573907100111001&#57;9nine
583A07200111010&#58;:colon
593B07300111011&#59;;
603C07400111100&#60;<less than
613D07500111101&#61;=equality sign
623E07600111110&#62;>greater than
633F07700111111&#63;?question mark
644010001000000&#64;@at sign
654110101000001&#65;A
664210201000010&#66;B
674310301000011&#67;C
684410401000100&#68;D
694510501000101&#69;E
704610601000110&#70;F
714710701000111&#71;G
724811001001000&#72;H
734911101001001&#73;I
744A11201001010&#74;J
754B11301001011&#75;K
764C11401001100&#76;L
774D11501001101&#77;M
784E11601001110&#78;N
794F11701001111&#79;O
805012001010000&#80;P
815112101010001&#81;Q
825212201010010&#82;R
835312301010011&#83;S
845412401010100&#84;T
855512501010101&#85;U
865612601010110&#86;V
875712701010111&#87;W
885813001011000&#88;X
895913101011001&#89;Y
905A13201011010&#90;Z
915B13301011011&#91;[left square bracket
925C13401011100&#92;\backslash
935D13501011101&#93;]right square bracket
945E13601011110&#94;^caret / circumflex
955F13701011111&#95;_underscore
966014001100000&#96;`grave / accent
976114101100001&#97;a
986214201100010&#98;b
996314301100011&#99;c
1006414401100100&#100;d
1016514501100101&#101;e
1026614601100110&#102;f
1036714701100111&#103;g
1046815001101000&#104;h
1056915101101001&#105;i
1066A15201101010&#106;j
1076B15301101011&#107;k
1086C15401101100&#108;l
1096D15501101101&#109;m
1106E15601101110&#110;n
1116F15701101111&#111;o
1127016001110000&#112;p
1137116101110001&#113;q
1147216201110010&#114;r
1157316301110011&#115;s
1167416401110100&#116;t
1177516501110101&#117;u
1187616601110110&#118;v
1197716701110111&#119;w
1207817001111000&#120;x
1217917101111001&#121;y
1227A17201111010&#122;z
1237B17301111011&#123;{left curly bracket
1247C17401111100&#124;|vertical bar
1257D17501111101&#125;}right curly bracket
1267E17601111110&#126;~tilde
1277F17701111111&#127;DELdelete

Extended ASCII Table
DecHexBinaryHTMLChar
1288010000000-€
1298110000001-
1308210000010-‚
1318310000011-ƒ
1328410000100-„
1338510000101-…
1348610000110-†
1358710000111-‡
1368810001000-ˆ
1378910001001-‰
1388A10001010-Š
1398B10001011-‹
1408C10001100-Œ
1418D10001101-
1428E10001110-Ž
1438F10001111-
1449010010000-
1459110010001-‘
1469210010010-’
1479310010011-“
1489410010100-”
1499510010101-•
1509610010110-–
1519710010111-—
1529810011000-˜
1539910011001-™
1549A10011010-š
1559B10011011-›
1569C10011100-œ
1579D10011101-
1589E10011110-ž
1599F10011111-Ÿ
160A010100000&#160;
161A110100001&#161;¡
162A210100010&#162;¢
163A310100011&#163;£
164A410100100&#164;¤
165A510100101&#165;¥
166A610100110&#166;¦
167A710100111&#167;§
168A810101000&#168;¨
169A910101001&#169;©
170AA10101010&#170;ª
171AB10101011&#171;«
172AC10101100&#172;¬
173AD10101101&#173;­
174AE10101110&#174;®
175AF10101111&#175;¯
176B010110000&#176;°
177B110110001&#177;±
178B210110010&#178;²
179B310110011&#179;³
180B410110100&#180;´
181B510110101&#181;µ
182B610110110&#182;
183B710110111&#183;·
184B810111000&#184;¸
185B910111001&#185;¹
186BA10111010&#186;º
187BB10111011&#187;»
188BC10111100&#188;¼
189BD10111101&#189;½
190BE10111110&#190;¾
191BF10111111&#191;¿
192C011000000&#192;À
193C111000001&#193;Á
194C211000010&#194;Â
195C311000011&#195;Ã
196C411000100&#196;Ä
197C511000101&#197;Å
198C611000110&#198;Æ
199C711000111&#199;Ç
200C811001000&#200;È
201C911001001&#201;É
202CA11001010&#202;Ê
203CB11001011&#203;Ë
204CC11001100&#204;Ì
205CD11001101&#205;Í
206CE11001110&#206;Î
207CF11001111&#207;Ï
208D011010000&#208;Ð
209D111010001&#209;Ñ
210D211010010&#210;Ò
211D311010011&#211;Ó
212D411010100&#212;Ô
213D511010101&#213;Õ
214D611010110&#214;Ö
215D711010111&#215;×
216D811011000&#216;Ø
217D911011001&#217;Ù
218DA11011010&#218;Ú
219DB11011011&#219;Û
220DC11011100&#220;Ü
221DD11011101&#221;Ý
222DE11011110&#222;Þ
223DF11011111&#223;ß
224E011100000&#224;à
225E111100001&#225;á
226E211100010&#226;â
227E311100011&#227;ã
228E411100100&#228;ä
229E511100101&#229;å
230E611100110&#230;æ
231E711100111&#231;ç
232E811101000&#232;è
233E911101001&#233;é
234EA11101010&#234;ê
235EB11101011&#235;ë
236EC11101100&#236;ì
237ED11101101&#237;í
238EE11101110&#238;î
239EF11101111&#239;ï
240F011110000&#240;ð
241F111110001&#241;ñ
242F211110010&#242;ò
243F311110011&#243;ó
244F411110100&#244;ô
245F511110101&#245;õ
246F611110110&#246;ö
247F711110111&#247;÷
248F811111000&#248;ø
249F911111001&#249;ù
250FA11111010&#250;ú
251FB11111011&#251;û
252FC11111100&#252;ü
253FD11111101&#253;ý
254FE11111110&#254;þ
255FF11111111&#255;ÿ


@classmethod

Description: Returns a class method for a function.

A class method receives the class as implicit first argument, just like an instance method receives the instance (i.e., self). To declare a class method, use this idiom:

class C:
@classmethod
def f(cls, arg1, arg2, ...): ...

The @classmethod form is a function decorator – see Function definitions for details.

A class method can be called either on the class (such as C.f()) or on an instance (such as C().f()). The instance is ignored except for its class. If a class method is called for a derived class, the derived class object is passed as the implied first argument.

Class methods are different than C++ or Java static methods. If you want those, see staticmethod(). For more information on class methods, see The standard type hierarchy.

Changed in version 3.9: Class methods can now wrap other descriptors such as property().

Examples: The classmethod syntax used to be classmethod(function) but was considered un-Pythonic; thus, in newer Python versions, you can use the @classmethod decorator for classmethod definitions.

Ex 1: Usage notes and difference from staticmethod

A class method is a method that is bound to a class rather than its object. It doesn't require creation of a class instance, much like staticmethod.

The difference between a static method and a class method is:

  • Static method knows nothing about the class and just deals with the parameters
  • Class method works with the class since its parameter is always the class itself.

The class method can be called both by the class and its object: Class.classmethod() or Class().classmethod(). Regardless, the class method is always attached to a class with the first argument as the class itself, cls:

class C:
@classmethod
def f(cls, arg1, arg2, ...): ...

Ex 2: Simple and equivalent usage of classmethod(function) and @classmethod

The code block

class Person:
age = 25

def printAge(cls):
print('The age is:', cls.age)

# create printAge class method
Person.printAge = classmethod(Person.printAge)
Person.printAge()

and

class Person:
age = 25

# create printAge class method
@classmethod
def printAge(cls):
print('The age is:', cls.age)

Person.printAge()

are effectively the same and have the following output:

The age is: 25

Notes: We have a Person class with a member variable age assigned to 25. We also have a function printAge that takes a single parameter cls and not self which is what we would usually take; that is, cls accepts the Person class as a parameter rather than Person instance we typically refer to by self.

For the classmethod(function) syntaxm, we pass the method Person.printAge as an argument to the classmethod function. This converts the method to a class method so that it accepts the first parameter as a class (i.e., Person). We then call printAge without creating a Person object like we do for static methods. This prints the class variable age.

The @classmethod function decorator form allows our code to be cleaner and is the more modern way to write Python code.


Ex 3: Using @classmethod to create a factory method

Factory methods are those methods that return a class object (similar to the __init__ constructor method which initializes the new instance of the class, self) for different use cases.

It is similar to function overloading in C++. Since, Python doesn't have anything as such, class methods and static methods are used.

from datetime import date

# random Person
class Person:
def __init__(self, name, age):
self.name = name
self.age = age

@classmethod
def fromBirthYear(cls, name, birthYear):
return cls(name, date.today().year - birthYear)

def display(self):
print(self.name + "'s age is: " + str(self.age))

person = Person('Adam', 19)
person.display()

person1 = Person.fromBirthYear('John', 1985)
person1.display()

Output:

Adam's age is: 19
John's age is: 36

The code block that produces the output above has two class instance creators, a constructor (i.e., __init__) and a fromBirthYear method.

The constructor takes its normal parameters, name and age in this case, while fromBirthYear takes cls (i.e., the Person class), name, and birthYear, and calculates the current age by subtracting the birthYear from the current year and returns the newly created class instance (the fact that fromBirthYear returns a new class instance is what makes it a factory method).

The fromBirthYear method takes the Person class (not a Person instance or object) as the first parameter, cls, and returns the constructor by calling cls(name, date.today().year - birthYear), which is equivalent to Person(name, date.today().year - birthYear).

Before the definition of the fromBirthYear method, we see @classmethod. This is called a decorator for converting fromBirthYear to a class method as classmethod().


Ex 4: How @classmethod works in the context of inheritance (and why @staticmethod would fail)

Whenever you derive a class from implementing a factory method as a class method, it ensures correct instance creation of the derived class. If, however, a factory method is implemented as a static method, then the instance created will always be hardcoded as the base class.

But when you use a class method, it creates the correct instance of the derived class. This is easier to understand by means of an example:

from datetime import date

# random Person
class Person:
def __init__(self, name, age):
self.name = name
self.age = age

@staticmethod
def fromFathersAge(name, fatherAge, fatherPersonAgeDiff):
# Cannot return cls(arg1, arg2, ...) or something like that since
# static methods know nothing about the class and deal strictly with the parameters
return Person(name, date.today().year - fatherAge + fatherPersonAgeDiff)

@classmethod
def fromBirthYear(cls, name, birthYear):
return cls(name, date.today().year - birthYear)

def display(self):
print(self.name + "'s age is: " + str(self.age))

class Man(Person):
sex = 'Male'

man_w_class_method = Man.fromBirthYear('John', 1985)
print(man_w_class_method)
print(isinstance(man_w_class_method, Man))
print(isinstance(man_w_class_method, Person))

man_w_static_method = Man.fromFathersAge('Bruce', 1965, 20)
print(man_w_static_method)
print(isinstance(man_w_static_method, Man))
print(isinstance(man_w_static_method, Person))

Output:

<__main__.Man object at 0x10dde4af0>
True
True

<__main__.Person object at 0x10dde49d0>
False
True

Using @staticmethod for the fromFathersAge factory method forces us to hardcode the instance tape (i.e., Person) during creation. This clearly causes a problem when Man inherits from Person.

The fromFathersAge method doesn't return a Man object but its base class, a hardcoded Person object. This violates the OOP paradigm. Using @classmethod for the fromBirthYear factory method can ensure the OOP-ness of the code since this method takes the first parameter as the class itself and calls its factory method.



compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)

Description: This StackOverflow answer gives a great somewhat dumbed down explanation (actual documentation reproduced below as an example): compile is a lower level version of exec and eval. It does not execute or evaluate your statements or expressions, but returns a code object that can do it. The modes are as follows:

  1. compile(string, '', 'eval') returns the code object that would have been executed had you done eval(string). Note that you cannot use statements in this mode; only a (single) expression is valid. Used for a single expression.
  2. compile(string, '', 'exec') returns the code object that would have been executed had you done exec(string). You can use any number of statements here. Used for an entire module.
  3. compile(string, '', 'single') is like the exec mode, but it will ignore everything except for the first statement. Note that an if/else statement with its results is considered a single statement. Used for one single statement. [Does not seem to be particularly useful.]

Examples:

Ex 0: Official documentation

Syntax: compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)

Compile the source into a code or AST object. Code objects can be executed by exec() or eval(). source can either be a normal string, a byte string, or an AST object. Refer to the ast module documentation for information on how to work with AST objects.

The filename argument should give the file from which the code was read; pass some recognizable value if it wasn't read from a file ('<string>' is commonly used).

The mode argument specifies what kind of code must be compiled; it can be 'exec' if source consists of a sequence of statements, 'eval' if it consists of a single expression, or 'single' if it consists of a single interactive statement (in the latter case, expression statements that evaluate to something other than None will be printed).

The optional arguments flags and dont_inherit control which compiler options should be activated and which future features should be allowed. If neither is present (or both are zero) the code is compiled with the same flags that affect the code that is calling compile(). If the flags argument is given and dont_inherit is not (or is zero) then the compiler options and the future statements specified by the flags argument are used in addition to those that would be used anyway. If dont_inherit is a non-zero integer then the flags argument is it – the flags (future features and compiler options) in the surrounding code are ignored.

Compiler options and future statements are specified by bits which can be bitwise ORed together to specify multiple options. The bitfield required to specify a given future feature can be found as the compiler_flag attribute on the _Feature instance in the __future__ module. Compiler flags can be found in ast module, with PyCF_ prefix.

The argument optimize specifies the optimization level of the compiler; the default value of -1 selects the optimization level of the interpreter as given by -O options. Explicit levels are 0 (no optimization; __debug__ is true), 1 (asserts are removed, __debug__ is false) or 2 (docstrings are removed too).

This function raises SyntaxError if the compiled source is invalid, and ValueError if the source contains null bytes.

If you want to parse Python code into its AST representation, see ast.parse().

Raises an auditing event compile with arguments source and filename. This event may also be raised by implicit compilation.

Note: When compiling a string with multi-line code in 'single' or 'eval' mode, input must be terminated by at least one newline character. This is to facilitate detection of incomplete and complete statements in the code module.

Warning: It is possible to crash the Python interpreter with a sufficiently large/complex string when compiling to an AST object due to stack depth limitations in Python's AST compiler.

Changed in version 3.2: Allowed use of Windows and Mac newlines. Also input in 'exec' mode does not have to end in a newline anymore. Added the optimize parameter.

Changed in version 3.5: Previously, TypeError was raised when null bytes were encountered in source.

New in version 3.8: ast.PyCF_ALLOW_TOP_LEVEL_AWAIT can now be passed in flags to enable support for top-level await, async for, and async with.


Ex 1: Examples and notes involving single, eval, and exec modes

As this helpful post illustrates, compile is meant to compile a source string from filename into a code object, which can later be executed by eval() or exec(). filename is simply used for run-time error messages. It is recommended to use '<string>' as the filename if source was not read from a file. mode is a string which indicates the compilation mode with the following options available:

  • 'single': indicates compilation is intended for a single statement
  • 'eval': indicates compilation is intended for a single expression
  • 'exec': indicates compliation is intended for an entire Python module

First, note that all expressions are statements (e.g., 5+5) in Python but not all statements are expressions (e.g., x = 5+5). Second, note that use of compile is rather infrequent. If you do find yourself using compile then you will likely use the exec mode. In any case, let's explore a few trivial use cases to illustrate usage.

Usage of compile with mode set to 'single': Suppose you have two files, example_usage.py and simple_module.py, in the same directory with contents as follows

# file: example_usage.py
with open('./simple_module.py') as f:
contents = f.read()

code_obj_single = compile(contents, 'simple_module.py', 'single')
exec(code_obj_single)
# file: simple_module.py
import json

def myfn(mydict):
return json.dumps(mydict)

def myfn2():
return myfn({"x": 30})

print(myfn2())

If we attempt to run example_usage.py, then we will get an error:

File "simple_module.py", line 1
import json
^
SyntaxError: multiple statements found while compiling a single statement

The error is exactly what it sounds like: Multiple statements currently exist in the simple_module.py file, but compile with the mode option set to 'single' is only meant to compile a single statement. Consider updating the example_usage.py and simple_module.py files as follows:

# file: example_usage.py
with open('./simple_module.py') as f:
contents = f.read()

code_obj_single = compile(contents, 'simple_module.py', 'single')
exec(code_obj_single)
print(json)
# file: simple_module.py
import json

Note that now simple_module.py only has a single statement in it, namely import json. We compile that single statement in example_usage.py and we can see that the statement has been executed via the print(json) statement:

<module 'json' from '/Users/danielfarlow/.pyenv/versions/3.9.4/lib/python3.9/json/__init__.py'>

Usage of compile with mode set to 'eval': Suppose you have two files, example_usage.py and simple_module.py, in the same directory with contents as follows

# file: example_usage.py
with open('./simple_module.py') as f:
contents = f.read()

code_obj_eval = compile(contents, 'simple_module.py', 'eval')
eval(code_obj_eval)
# file: simple_module.py
import json

If we attempt to run example_usage.py, then we will get an error:

File "simple_module.py", line 1
import json
^
SyntaxError: invalid syntax

Why do we get this error? Because when 'eval' is chosen as the mode option we can only use an expression (singular) as the source. Remember that all expressions are statements but not all statements are expressions (expressions must resolve to a value). Suppose you change example_usage.py and simple_module.py in the following manner:

# file: example_usage.py
with open('./simple_module.py') as f:
contents = f.read()

code_obj_eval = compile(contents, 'simple_module.py', 'eval')
# file: simple_module.py
"2+3"
"5+10"

Will we get an error when running the example_usage.py file? Yes:

File "simple_module.py", line 2
"5+10"
^
SyntaxError: invalid syntax

Why do we get this error? Because we have more than one expression. Update the simple_module.py file to have "2+3" as its only line, and update the example_usage.py as well:

# file: example_usage.py
with open('./simple_module.py') as f:
contents = f.read()

code_obj_eval = compile(contents, 'simple_module.py', 'eval')
num = eval(code_obj_eval)
print(num)
# file: simple_module.py
"2+3"

What do you think the output will be upon running the example_usage.py file? You might be surprised when you get 2+3 as the output. Why didn't eval actually evaluate "2+3" like we might have suspected? The easiest way to see this is probably by means of updating the example_usage.py file and running it again:

# file: example_usage.py
with open('./simple_module.py') as f:
contents = f.read()
print("===== BEGIN READING FILE CONTENTS =====")
print(dir(contents))
print(type(contents))
print("===== END READING FILE CONTENTS =====")

code_obj_eval = compile(contents, 'simple_module.py', 'eval')
print("===== BEGIN ATTRIBUTES OF COMPILED FILE CONTENTS OBJECT =====")
print(dir(code_obj_eval))
print("===== END ATTRIBUTES OF COMPILED FILE CONTENTS OBJECT =====")
print("Type of code object: ", type(code_obj_eval))
print("Type of evaluated code object: ", type(eval(code_obj_eval)))
# file: simple_module.py
"2+3"

Output:

===== BEGIN READING FILE CONTENTS =====
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'removeprefix', 'removesuffix', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
<class 'str'>
===== END READING FILE CONTENTS =====
===== BEGIN ATTRIBUTES OF COMPILED FILE CONTENTS OBJECT =====
['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'co_argcount', 'co_cellvars', 'co_code', 'co_consts', 'co_filename', 'co_firstlineno', 'co_flags', 'co_freevars', 'co_kwonlyargcount', 'co_lnotab', 'co_name', 'co_names', 'co_nlocals', 'co_posonlyargcount', 'co_stacksize', 'co_varnames', 'replace']
===== END ATTRIBUTES OF COMPILED FILE CONTENTS OBJECT =====
Type of code object: <class 'code'>
Type of evaluated code object: <class 'str'>

Some reflection seems to indicate that evaluating a code object essenitally "unwraps" the code object so we get the original code, namely a string in this case: "2+3". If we then want to evaluate that string, we must use eval again (hence twice):

# file: example_usage.py
with open('./simple_module.py') as f:
contents = f.read()

code_obj_eval = compile(contents, 'simple_module.py', 'eval')
num = eval(eval(code_obj_eval))
print(num)
# file: simple_module.py
"2+3"

The output is then more in line with what we might normally expect: 5. This behavior suggests a way we could avoid all of this rigmarole entirely: instead of writing "2+3" in the simple_module.py file, why not simply have 2+3 which will be stringified upon reading and then effectively evaluated when eval is applied after compile? We can avoid the double use of eval in such a case. Hence, we could have the following which would also have an output of 5 (note how there is now only one use of eval in example_usage.py and the "2+3" is now simply 2+3 in the simple_module.py file):

# file: example_usage.py
with open('./simple_module.py') as f:
contents = f.read()

code_obj_eval = compile(contents, 'simple_module.py', 'eval')
num = eval(code_obj_eval)
print(num)
# file: simple_module.py
2+3

Usage of compile with mode set to 'exec': If you find yourself using compile, then odds are this will be how you use it! Suppose you have two files, example_usage.py and simple_module.py, in the same directory with contents as follows:

# file: example_usage.py
with open('./simple_module.py') as f:
contents = f.read()

code_obj_exec = compile(contents, 'simple_module.py', 'exec')
exec(code_obj_exec)
# file: simple_module.py
import json

def myfn(mydict):
return json.dumps(mydict)

def myfn2():
return myfn({"x": 30})

print(myfn2())

If we attempt to run example_usage.py, then we will get what we might expect:

{"x": 30}

Furthermore, if we tried to execute a statement like print(myfn) from within example_usage.py, then we would get something like <function myfn at 0x10ba9fca0> which indicates the myfn function has been read in effectively from the simple_module.py file.



complex([real[, imag]])

Description: The complex() method returns a complex number when real and imaginary parts are provided, or it converts a string to a complex number.

The syntax of complex() is:

complex([real[, imag]])

In general, complex() method takes two parameters:

  • real - real part. If real is omitted, it defaults to 0.
  • imag - imaginary part. If imag is omitted, it defaults to 0.

If the first parameter passed to this method is a string, it will be interpreted as a complex number. In this case, the second parameter shouldn't be passed.

As suggested by the name, complex() method returns a complex number. If the string passed to this method is not a valid complex number, ValueError exception is raised.

Note: The string passed to complex() should be in the form real+imagj or real+imagJ.

Examples:

Ex 0: Documentation

Return a complex number with the value real + imag*1j or convert a string or number to a complex number. If the first parameter is a string, it will be interpreted as a complex number and the function must be called without a second parameter. The second parameter can never be a string. Each argument may be any numeric type (including complex). If imag is omitted, it defaults to zero and the constructor serves as a numeric conversion like int and float. If both arguments are omitted, returns 0j.

For a general Python object x, complex(x) delegates to x.__complex__(). If __complex__() is not defined then it falls back to __float__(). If __float__() is not defined then it falls back to __index__().

Note: When converting from a string, the string must not contain whitespace around the central + or - operator. For example, complex('1+2j') is fine, but complex('1 + 2j') raises ValueError.

The complex type is described in Numeric Types — int, float, complex.

Changed in version 3.6: Grouping digits with underscores as in code literals is allowed.

Changed in version 3.8: Falls back to __index__() if __complex__() and __float__() are not defined.


Ex 1: How to create a complex number in Python?
z = complex(2, -3)
print(z)

z = complex(1)
print(z)

z = complex()
print(z)

z = complex('5-9j')
print(z)

Output:

(2-3j)
(1+0j)
0j
(5-9j)

Ex 2: Create complex Number Without Using complex()

It's possible to create a complex number without using the complex() method explicitly. For that, you have to put 'j' or 'J' after a number.

a = 2+3j
print('a =',a)
print('Type of a is',type(a))

b = -2j
print('b =',b)
print('Type of b is',type(a))

c = 0j
print('c =',c)
print('Type of c is',type(c))

Output:

a = (2+3j)
Type of a is <class 'complex'>
b = (-0-2j)
Type of b is <class 'complex'>
c = 0j
Type of c is <class 'complex'>


delattr(object, name)

Description: The delattr() built-in deletes an attribute from the provided object (if the object allows it).

The syntax of delattr() is:

delattr(object, name)

delattr() takes two parameters:

  • object - the object from which name attribute is to be removed
  • name - a string which must be the name of the attribute to be removed from the object

delattr() doesn't return any value (returns None). It only removes an attribute (if the object allows it).

Examples:

Ex 0: Documentation

This is a relative of setattr(). The arguments are an object and a string. The string must be the name of one of the object's attributes. The function deletes the named attribute, provided the object allows it. For example, delattr(x, 'foobar') is equivalent to del x.foobar.


Ex 1: How delattr() works?
class Coordinate:
x = 10
y = -5
z = 0

point1 = Coordinate()

print('x = ',point1.x)
print('y = ',point1.y)
print('z = ',point1.z)

delattr(Coordinate, 'z')

print('--After deleting z attribute--')
print('x = ',point1.x)
print('y = ',point1.y)

# Raises Error
print('z = ',point1.z)

Output:

x =  10
y = -5
z = 0
--After deleting z attribute--
x = 10
y = -5
Traceback (most recent call last):
File "/Volumes/DEVFARLOW/development-and-engineering/python-learnings/mymodule.py", line 19, in <module>
print('z = ',point1.z)
AttributeError: 'Coordinate' object has no attribute 'z'

Ex 2: Deleting attribute using del operator

You can also delete attribute of an object using del operator.

class Coordinate:
x = 10
y = -5
z = 0

point1 = Coordinate()

print('x = ',point1.x)
print('y = ',point1.y)
print('z = ',point1.z)

# Deleting attribute z
del Coordinate.z

print('--After deleting z attribute--')
print('x = ',point1.x)
print('y = ',point1.y)

# Raises Attribute Error
print('z = ',point1.z)

The output of the program will be the same as in Example 1.



dict(**kwarg); dict(mapping, **kwarg); dict(iterable, **kwarg)

Description: The dict() constructor creates a dictionary in Python. Different forms of dict() constructors are:

class dict(**kwarg)
class dict(mapping, **kwarg)
class dict(iterable, **kwarg)

Note: **kwarg lets you take an arbitrary number of keyword arguments.

A keyword argument is an argument preceded by an identifier (e.g., name=). Hence, the keyword argument of the form kwarg=value is passed to the dict() constructor to create dictionaries.

dict() doesn't return any value (returns None).

Examples:

Ex 0: Documentation
class dict(**kwarg) class dict(mapping, **kwarg) class dict(iterable, **kwarg)

Create a new dictionary. The dict object is the dictionary class. See dict and Mapping Types — dict for documentation about this class.

For other containers see the built-in list, set, and tuple classes, as well as the collections module.


Ex 1: Create dictionary using keyword arguments only
numbers = dict(x=5, y=0)
print('numbers =', numbers)
print(type(numbers))

empty = dict()
print('empty =', empty)
print(type(empty))

Output:

numbers = {'x': 5, 'y': 0}
<class 'dict'>
empty = {}
<class 'dict'>

Ex 2: Create dictionary using an iterable
# keyword argument is not passed
numbers1 = dict([('x', 5), ('y', -5)])
print('numbers1 =',numbers1)

# keyword argument is also passed
numbers2 = dict([('x', 5), ('y', -5)], z=8)
print('numbers2 =',numbers2)

# zip() creates an iterable in Python 3
numbers3 = dict(dict(zip(['x', 'y', 'z'], [1, 2, 3])))
print('numbers3 =',numbers3)

Output:

numbers1 = {'x': 5, 'y': -5}
numbers2 = {'x': 5, 'y': -5, 'z': 8}
numbers3 = {'x': 1, 'y': 2, 'z': 3}

Ex 3: Create dictionary using mapping
numbers1 = dict({'x': 4, 'y': 5})
print('numbers1 =',numbers1)

# you don't need to use dict() in above code
numbers2 = {'x': 4, 'y': 5}
print('numbers2 =',numbers2)

# keyword argument is also passed
numbers3 = dict({'x': 4, 'y': 5}, z=8)
print('numbers3 =',numbers3)

Output:

numbers1 = {'x': 4, 'y': 5}
numbers2 = {'x': 4, 'y': 5}
numbers3 = {'x': 4, 'y': 5, 'z': 8}


dir([object])

Description: The dir() method tries to return a list of valid attributes of the object.

The syntax of dir() is:

dir([object])

dir() takes maximum of one object.

  • object (optional) - dir() attempts to return all attributes of this object.

dir() tries to return a list of valid attributes of the object.

  • If the object has __dir__() method, the method will be called and must return the list of attributes.
  • If the object doesn't have __dir__() method, this method tries to find information from the __dict__ attribute (if defined), and from type object. In this case, the list returned from dir() may not be complete.

If an object is not passed to dir() method, it returns the list of names in the current local scope.

Examples:

Ex 0: Documentation

Without arguments, return the list of names in the current local scope. With an argument, attempt to return a list of valid attributes for that object.

If the object has a method named __dir__(), this method will be called and must return the list of attributes. This allows objects that implement a custom __getattr__() or __getattribute__() function to customize the way dir() reports their attributes.

If the object does not provide __dir__(), the function tries its best to gather information from the object's __dict__ attribute, if defined, and from its type object. The resulting list is not necessarily complete, and may be inaccurate when the object has a custom __getattr__().

The default dir() mechanism behaves differently with different types of objects, as it attempts to produce the most relevant, rather than complete, information:

  • If the object is a module object, the list contains the names of the module's attributes.
  • If the object is a type or class object, the list contains the names of its attributes, and recursively of the attributes of its bases.
  • Otherwise, the list contains the object's attributes' names, the names of its class's attributes, and recursively of the attributes of its class's base classes.

The resulting list is sorted alphabetically. For example:

>>> import struct
>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'struct']
>>> class Shape:
... def __dir__(self):
... return ['area', 'perimeter', 'location']
...
>>> s = Shape()
>>> dir(s)
['area', 'location', 'perimeter']
>>>

Note: Because dir() is supplied primarily as a convenience for use at an interactive prompt, it tries to supply an interesting set of names more than it tries to supply a rigorously or consistently defined set of names, and its detailed behavior may change across releases. For example, metaclass attributes are not in the result list when the argument is a class.


Ex 1: How dir() works?
number = [1, 2, 3]
print(dir(number))

print('\nReturn Value from empty dir()')
print(dir())

Output:

['__add__', '__class__', '__class_getitem__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

Return Value from empty dir()
['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'number']

Note how 'number' is included in the list when we print dir() with no provided object.


Ex 2: dir() on user-defined object
class Person:
def __dir__(self):
return ['age', 'name', 'salary']


teacher = Person()
print(dir(teacher))

Output:

['age', 'name', 'salary']


divmod(a,b)

Description: The divmod() method takes two numbers and returns a pair of numbers (a tuple) consisting of their quotient and remainder.

The syntax of divmod() is:

divmod(x, y)

divmod() takes two parameters:

  • x - a non-complex number (numerator)
  • y - a non-complex number (denominator)

divmod() returns

  • (q, r) - a pair of numbers (a tuple) consisting of quotient q and remainder r

If x and y are integers, the return value from divmod() is same as (a // b, x % y).

If either x or y is a float, the result is (q, x % y). Here, q is the whole part of the quotient.

Examples:

Ex 0: Documentation

Take two (non complex) numbers as arguments and return a pair of numbers consisting of their quotient and remainder when using integer division. With mixed operand types, the rules for binary arithmetic operators apply. For integers, the result is the same as (a // b, a % b). For floating point numbers the result is (q, a % b), where q is usually math.floor(a / b) but may be 1 less than that. In any case q * b + a % b is very close to a, if a % b is non-zero it has the same sign as b, and 0 <= abs(a % b) < abs(b).


Ex 1: How divmod() works in Python?
print('divmod(8, 3) = ', divmod(8, 3))
print('divmod(3, 8) = ', divmod(3, 8))
print('divmod(5, 5) = ', divmod(5, 5))

# divmod() with Floats
print('divmod(8.0, 3) = ', divmod(8.0, 3))
print('divmod(3, 8.0) = ', divmod(3, 8.0))
print('divmod(7.5, 2.5) = ', divmod(7.5, 2.5))
print('divmod(2.6, 0.5) = ', divmod(2.6, 0.5))

divmod(8, 3) = (2, 2) divmod(3, 8) = (0, 3) divmod(5, 5) = (1, 0) divmod(8.0, 3) = (2.0, 2.0) divmod(3, 8.0) = (0.0, 3.0) divmod(7.5, 2.5) = (3.0, 0.0) divmod(2.6, 0.5) = (5.0, 0.10000000000000009)



enumerate(iterable, start=0)

Description: The enumerate() method adds a counter to an iterable and returns it (the enumerate object).

languages = ['Python', 'Java', 'JavaScript']

enumerate_prime = enumerate(languages)

# convert enumerate object to list
print(list(enumerate_prime))

# Output: [(0, 'Python'), (1, 'Java'), (2, 'JavaScript')]

The syntax of enumerate() is:

enumerate(iterable, start=0)

enumerate() method takes two parameters:

  • iterable - a sequence, an iterator, or objects that supports iteration
  • start (optional) - enumerate() starts counting from this number. If start is omitted, 0 is taken as start.

enumerate() method adds counter to an iterable and returns it. The returned object is an enumerate object.

You can convert enumerate objects to a list or a tuple using the list() and tuple() methods, respectively.

Examples:

Ex 0: Documentation

Return an enumerate object. iterable must be a sequence, an iterator, or some other object which supports iteration. The __next__() method of the iterator returned by enumerate() returns a tuple containing a count (from start which defaults to 0) and the values obtained from iterating over iterable.

>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]

Equivalent to:

def enumerate(sequence, start=0):
n = start
for elem in sequence:
yield n, elem
n += 1

Ex 1: How enumerate() works in Python?
grocery = ['bread', 'milk', 'butter']
enumerateGrocery = enumerate(grocery)

print(type(enumerateGrocery))

# converting to list
print(list(enumerateGrocery))

# changing the default counter
enumerateGrocery = enumerate(grocery, 10)
print(list(enumerateGrocery))

Output:

<class 'enumerate'>
[(0, 'bread'), (1, 'milk'), (2, 'butter')]
[(10, 'bread'), (11, 'milk'), (12, 'butter')]

Ex 2: Looping over an enumerator object
grocery = ['bread', 'milk', 'butter']

for item in enumerate(grocery):
print(item)

print('\n')

for count, item in enumerate(grocery):
print(count, item)

print('\n')
# changing default start value
for count, item in enumerate(grocery, 100):
print(count, item)

Output:

(0, 'bread')
(1, 'milk')
(2, 'butter')

0 bread
1 milk
2 butter

100 bread
101 milk
102 butter


eval(expression[, globals[, locals]])

Description: The eval() method parses the expression passed to this method and runs python expression (code) within the program.

number = 9

# eval performs the multiplication passed as argument
square_number = eval('number * number')
print(square_number)

# Output: 81

The syntax of eval() is:

eval(expression, globals=None, locals=None)

The eval() function takes three parameters:

  • expression - the string parsed and evaluated as a Python expression
  • globals (optional) - a dictionary
  • locals (optional)- a mapping object. Dictionary is the standard and commonly used mapping type in Python.

The use of globals and locals will be discussed more below in the examples.

The eval() method returns the result evaluated from the expression.

Warnings when using eval(): Consider a situation where you are using a Unix-like system (macOS, Linux, etc) and you have imported the os module. The os module provides a portable way to use operating system functionalities like reading or writing to a file.

If you allow users to input a value using eval(input()), the user may issue commands to change the file or even delete all the files using the command os.system('rm -rf *').

If you are using eval(input()) in your code, it is a good idea to check which variables and methods the user can use. You can see which variables and methods are available using the dir() method.

from math import *
print(eval('dir()'))

Output:

['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'comb', 'copysign', 'cos', 'cosh', 'degrees', 'dist', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'isqrt', 'lcm', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'nextafter', 'perm', 'pi', 'pow', 'prod', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc', 'ulp']

Restricting the use of available methods and variables in eval() via globals and locals parameters: More often than not, all the available methods and variables used in the expression (first parameter to eval()) may not be needed, or even may have a security hole. You may need to restrict the use of these methods and variables for eval(). You can do so by passing optional globals and locals parameters (dictionaries) to the eval() function.

  1. Both globals and locals parameters are omitted: If both parameters are omitted (as in our earlier examples), the expression is executed in the current scope. You can check the available variables and methods using following code: print(eval('dir()')

  2. Passing globals parameter; locals parameter is omitted: The globals and locals parameters (dictionaries) are used for global and local variables respectively. If the locals dictionary is omitted, it defaults to globals dictionary. Meaning, globals will be used for both global and local variables.

Note: You can check the current global and local dictionary in Python using globals() and locals() built-in methods respectively.

  1. Passing both globals and locals dictionaries: You can make needed functions and variables available for use by passing the locals dictionary. For example:
from math import *

a = 169
print(eval('sqrt(a)', {'__builtins__': None}, {'a': a, 'sqrt': sqrt}))

In this program, expression can have sqrt() method and variable a only. All other methods and variables are unavailable.

Restricting the use of eval() by passing globals and locals dictionaries will make your code secure particularly when you are using input provided by the user to the eval() method.

Note: Sometimes, eval() is not secure even with limited names. When an object and its methods are made accessible, almost anything can be done. The only secure way is by validating the user input.

Examples:

Ex 0: Documentation

The arguments are a string and optional globals and locals. If provided, globals must be a dictionary. If provided, locals can be any mapping object.

The expression argument is parsed and evaluated as a Python expression (technically speaking, a condition list) using the globals and locals dictionaries as global and local namespace. If the globals dictionary is present and does not contain a value for the key __builtins__, a reference to the dictionary of the built-in module builtins is inserted under that key before expression is parsed. This means that expression normally has full access to the standard builtins module and restricted environments are propagated. If the locals dictionary is omitted it defaults to the globals dictionary. If both dictionaries are omitted, the expression is executed with the globals and locals in the environment where eval() is called. Note, eval() does not have access to the nested scopes (non-locals) in the enclosing environment.

The return value is the result of the evaluated expression. Syntax errors are reported as exceptions. Example:

>>> x = 1
>>> eval('x+1')
2

This function can also be used to execute arbitrary code objects (such as those created by compile()). In this case pass a code object instead of a string. If the code object has been compiled with 'exec' as the mode argument, eval()'s return value will be None.

Hints: dynamic execution of statements is supported by the exec() function. The globals() and locals() functions returns the current global and local dictionary, respectively, which may be useful to pass around for use by eval() or exec().

See ast.literal_eval() for a function that can safely evaluate strings with expressions containing only literals.

Raises an auditing event exec with the code object as the argument. Code compilation events may also be raised.


Ex 1: How eval() works in Python
x = 1
print(eval('x + 1'))

Output:

2

Here, the eval() function evaluates the expression x + 1 and print is used to display this value.


Ex 2: Practical example to demonstrate use of eval()
# Perimeter of Square
def calculatePerimeter(l):
return 4*l

# Area of Square
def calculateArea(l):
return l*l

expression = input("Type a function: ")

for l in range(1, 5):
if (expression == 'calculatePerimeter(l)'):
print("If length is ", l, ", Perimeter = ", eval(expression))
elif (expression == 'calculateArea(l)'):
print("If length is ", l, ", Area = ", eval(expression))
else:
print('Wrong Function')
break

Output:

Type a function: calculateArea(l)
If length is 1 , Area = 1
If length is 2 , Area = 4
If length is 3 , Area = 9
If length is 4 , Area = 16

Ex 3: Passing empty dictionary as globals parameter
from math import *
print(eval('dir()', {}))

# The code will raise an exception
print(eval('sqrt(25)', {}))

Output:

['__builtins__']
Traceback (most recent call last):
File "<string>", line 5, in <module>
print(eval('sqrt(25)', {}))
File "<string>", line 1, in <module>
NameError: name 'sqrt' is not defined

If you pass an empty dictionary as globals, only the __builtins__ are available to expression (first parameter to the eval()).

Even though we have imported the math module in the above program, expression can't access any functions provided by the math module.


Ex 4: Making certain methods available
from math import *
print(eval('dir()', {'sqrt': sqrt, 'pow': pow}))
print(eval('sqrt(4)', { 'sqrt': sqrt }))

Output:

['__builtins__', 'pow', 'sqrt']
2.0

Here, the first expression can only use the sqrt() and the pow() methods along with __builtins__ while the second expression can only use the sqrt() method along with __builtins__.

It is also possible to change the name of the method available for the expression as you wish:

from math import *
names = {'square_root': sqrt, 'power': pow}
print(eval('dir()', names))

# Using square_root in Expression
print(eval('square_root(9)', names))

Output:

['__builtins__', 'power', 'square_root']
3.0

In the above program, square_root() calculates the square root using sqrt(). However, trying to use sqrt() directly will raise an error.


Ex 5: Restricting the use of built-ins

You can restrict the use of __builtins__ in the expression as follows:

eval(expression, {'__builtins__': None})


exec(object[, globals[, locals]])

Description: The exec() method executes the dynamically created program, which is either a string or a code object.

The syntax of exec():

exec(object, globals, locals)

exec() takes three parameters:

  • object - Either a string or a code object
  • globals (optional) - a dictionary
  • locals (optional)- a mapping object. Dictionary is the standard and commonly used mapping type in Python.

The use of globals and locals will be discussed throughout the examples.

exec() doesn't return any value, it returns None.

Be careful when using exec(): Consider a situation, you are using a Unix-like system (macOS, Linux etc) and you have imported the os module. The os module provides a portable way to use operating system functionalities like read or write a file.

If you allow users to input a value using exec(input()), the user may issue commands to change the file or even delete all the files using the command os.system('rm -rf *').

If you are using exec(input()) in your code, it's a good idea to check which variables and methods the user can use. You can see which variables and methods are available using the dir() method.

from math import *
exec('print(dir())')

Output:

['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'comb', 'copysign', 'cos', 'cosh', 'degrees', 'dist', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'isqrt', 'lcm', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'nextafter', 'perm', 'pi', 'pow', 'prod', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc', 'ulp']

Restricting the use of available methods and variables in exec() via globals and locals parameters: More often than not, all the available methods and variables used in exec() may not be needed, or even may have a security hole. You can restrict the use of these variables and methods by passing optional globals and locals parameters (dictionaries) to the exec() method.

  1. Both globals and locals parameters are omitted: If both parameters are omitted (as in our earlier examples), the code expected to be executed by exec() is executed in the current scope. You can check the available variables and methods using the following code: exec('print(dir())')

  2. Passing globals parameter; locals parameter is omitted: The globals and locals parameters (dictionaries) are used for global and local variables respectively. If the locals dictionary is omitted, it defaults to globals dictionary. Meaning, globals will be used for both global and local variables.

Note: You can check the current global and local dictionary in Python using globals() and locals() built-in methods respectively.

  1. Passing empty dictionary as globals parameter:
from math import *
exec('print(dir())', {})

# This code will raise an exception
# exec('print(sqrt(9))', {})

Output:

['__builtins__']

If you pass an empty dictionary as globals, only the __builtins__ are available to the object (first parameter to exec()). Even though we have imported the math module in the above program, trying to access any of the functions provided by the math module will raise an exception.

Making certain methods available:

from math import *
exec('print(dir())', {'sqrt': sqrt, 'pow': pow})

# object can have sqrt() module
exec('print(sqrt(9))', {'sqrt': sqrt, 'pow': pow})

Here, the code that is executed by exec() can also have sqrt() and pow() methods along with __builtins__.

It's possible to change the name of the method as you wish:

from math import *
exec('print(dir())', {'squareRoot': sqrt, 'pow': pow})

# object can have squareRoot() module
exec('print(squareRoot(9))', {'squareRoot': sqrt, 'pow': pow})

In the above program, squareRoot() calculates the square root (similar functionality like sqrt()). However, trying to use sqrt() will raise an exception.

Restricting the use of built-ins: You can restrict the use of __builtins__ by giving value None to the '__builtins__' in the globals dictionary:

exec(object, {'__builtins__': None}) 
  1. Passing both globals and locals dictionaries: You can make needed functions and variables available for use by passing the locals dictionary. For example:
from math import *

globalsParameter = {'__builtins__' : None}
localsParameter = {'print': print, 'dir': dir}
exec('print(dir())', globalsParameter, localsParameter)

Output:

['dir', 'print']

Here, only two built-in methods print() and dir() can be executed by exec() method.

It's important to note that, exec() executes the code and doesn't return any value (returns None). Hence, you cannot use return and yield statements outside of the function definitions.

Examples:

Ex 0: Documentation

This function supports dynamic execution of Python code. object must be either a string or a code object. If it is a string, the string is parsed as a suite of Python statements which is then executed (unless a syntax error occurs). [Note that the parser only accepts the Unix-style end of line convention. If you are reading the code from a file, make sure to use newline conversion mode to convert Windows or Mac-style newlines.] If it is a code object, it is simply executed. In all cases, the code that's executed is expected to be valid as file input (see the section "File input" in the Reference Manual). Be aware that the nonlocal, yield, and return statements may not be used outside of function definitions even within the context of code passed to the exec() function. The return value is None.

In all cases, if the optional parts are omitted, the code is executed in the current scope. If only globals is provided, it must be a dictionary (and not a subclass of dictionary), which will be used for both the global and the local variables. If globals and locals are given, they are used for the global and local variables, respectively. If provided, locals can be any mapping object. Remember that at module level, globals and locals are the same dictionary. If exec gets two separate objects as globals and locals, the code will be executed as if it were embedded in a class definition.

If the globals dictionary does not contain a value for the key __builtins__, a reference to the dictionary of the built-in module builtins is inserted under that key. That way you can control what builtins are available to the executed code by inserting your own __builtins__ dictionary into globals before passing it to exec().

Raises an auditing event exec with the code object as the argument. Code compilation events may also be raised.

Note: The built-in functions globals() and locals() return the current global and local dictionary, respectively, which may be useful to pass around for use as the second and third argument to exec().

Note: The default locals act as described for function locals() below: modifications to the default locals dictionary should not be attempted. Pass an explicit locals dictionary if you need to see effects of the code on locals after function exec() returns.


Ex 1: How exec() works?
program = 'a = 5\nb=10\nprint("Sum =", a+b)'
exec(program)

Output:

Sum = 15

Here, the string object program is passed to exec() which executes the program. globals and locals are omitted in this case.


Ex 2: Allow user to provide input
program = input('Enter a program:')
exec(program)

Output:

Enter a program: [print(item) for item in [1, 2, 3]]
1
2
3

If you want to take Python code from the user which allows multiline code (using '\n'), you can use the compile() method before using exec().



filter(function, iterable)

Description: tbd

Examples:

Ex 0: Documentation

Construct an iterator from those elements of iterable for which function returns true. iterable may be either a sequence, a container which supports iteration, or an iterator. If function is None, the identity function is assumed, that is, all elements of iterable that are false are removed.

Note that filter(function, iterable) is equivalent to the generator expression (item for item in iterable if function(item)) if function is not None and (item for item in iterable if item) if function is None.

See itertools.filterfalse() for the complementary function that returns elements of iterable for which function returns false.



float([x])

Description: tbd

Examples:

Ex 0: Documentation

Return a floating point number constructed from a number or string x.

If the argument is a string, it should contain a decimal number, optionally preceded by a sign, and optionally embedded in whitespace. The optional sign may be '+' or '-'; a '+' sign has no effect on the value produced. The argument may also be a string representing a NaN (not-a-number), or a positive or negative infinity. More precisely, the input must conform to the following grammar after leading and trailing whitespace characters are removed:

sign           ::=  "+" | "-"infinity       ::=  "Infinity" | "inf"nan            ::=  "nan"numeric_value  ::=  floatnumber | infinity | nannumeric_string ::=  [sign] numeric_value

Here floatnumber is the form of a Python floating-point literal, described in Floating point literals. Case is not significant, so, for example, "inf", "Inf", "INFINITY" and "iNfINity" are all acceptable spellings for positive infinity.

Otherwise, if the argument is an integer or a floating point number, a floating point number with the same value (within Python's floating point precision) is returned. If the argument is outside the range of a Python float, an OverflowError will be raised.

For a general Python object x, float(x) delegates to x.__float__(). If __float__() is not defined then it falls back to __index__().

If no argument is given, 0.0 is returned.

Examples:

>>> float('+1.23')
1.23
>>> float(' -12345\n')
-12345.0
>>> float('1e-003')
0.001
>>> float('+1E6')
1000000.0
>>> float('-Infinity')
-inf

The float type is described in Numeric Types — int, float, complex.

Changed in version 3.6: Grouping digits with underscores as in code literals is allowed.

Changed in version 3.7: x is now a positional-only parameter.

Changed in version 3.8: Falls back to __index__() if __float__() is not defined.



format(value[, format_spec])

Description: tbd

Examples:

Ex 0: Documentation

Convert a value to a "formatted" representation, as controlled by format_spec. The interpretation of format_spec will depend on the type of the value argument, however there is a standard formatting syntax that is used by most built-in types: Format Specification Mini-Language.

The default format_spec is an empty string which usually gives the same effect as calling str(value).

A call to format(value, format_spec) is translated to type(value).__format__(value, format_spec) which bypasses the instance dictionary when searching for the value's __format__() method. A TypeError exception is raised if the method search reaches object and the format_spec is non-empty, or if either the format_spec or the return value are not strings.

Changed in version 3.4: object().__format__(format_spec) raises TypeError if format_spec is not an empty string.



frozenset([iterable])

Description: tbd

Examples:

Ex 0: Documentation

Return a new frozenset object, optionally with elements taken from iterable. frozenset is a built-in class. See frozenset and Set Types — set, frozenset for documentation about this class.

For other containers see the built-in set, list, tuple, and dict classes, as well as the collections module.



getattr(object, name[, default])

Description: tbd

Examples:

Ex 0: Documentation

Return the value of the named attribute of object. name must be a string. If the string is the name of one of the object's attributes, the result is the value of that attribute. For example, getattr(x, 'foobar') is equivalent to x.foobar. If the named attribute does not exist, default is returned if provided, otherwise AttributeError is raised.

Note: Since private name mangling happens at compilation time, one must manually mangle a private attribute's (attributes with two leading underscores) name in order to retrieve it with getattr().



globals()

Description: tbd

Examples:

Ex 0: Documentation

Return a dictionary representing the current global symbol table. This is always the dictionary of the current module (inside a function or method, this is the module where it is defined, not the module from which it is called).



hasattr(object, name)

Description: tbd

Examples:

Ex 0: Documentation

The arguments are an object and a string. The result is True if the string is the name of one of the object's attributes, False if not. (This is implemented by calling getattr(object, name) and seeing whether it raises an AttributeError or not.)



hash(object)

Description: tbd

Examples:

Ex 0: Documentation

Return the hash value of the object (if it has one). Hash values are integers. They are used to quickly compare dictionary keys during a dictionary lookup. Numeric values that compare equal have the same hash value (even if they are of different types, as is the case for 1 and 1.0).

Note: For objects with custom __hash__() methods, note that hash() truncates the return value based on the bit width of the host machine. See __hash__() for details.



help([object])

Description: tbd

Examples:

Ex 0: Documentation

Invoke the built-in help system. (This function is intended for interactive use.) If no argument is given, the interactive help system starts on the interpreter console. If the argument is a string, then the string is looked up as the name of a module, function, class, method, keyword, or documentation topic, and a help page is printed on the console. If the argument is any other kind of object, a help page on the object is generated.

Note that if a slash(/) appears in the parameter list of a function, when invoking help(), it means that the parameters prior to the slash are positional-only. For more info, see the FAQ entry on positional-only parameters.

This function is added to the built-in namespace by the site module.

Changed in version 3.4: Changes to pydoc and inspect mean that the reported signatures for callables are now more comprehensive and consistent.



hex(x)

Description: tbd

Examples:

Ex 0: Documentation

Convert an integer number to a lowercase hexadecimal string prefixed with "0x". If x is not a Python int object, it has to define an __index__() method that returns an integer. Some examples:

>>> hex(255)
'0xff'
>>> hex(-42)
'-0x2a'

If you want to convert an integer number to an uppercase or lower hexadecimal string with prefix or not, you can use either of the following ways:

>>> '%#x' % 255, '%x' % 255, '%X' % 255
('0xff', 'ff', 'FF')
>>> format(255, '#x'), format(255, 'x'), format(255, 'X')
('0xff', 'ff', 'FF')
>>> f'{255:#x}', f'{255:x}', f'{255:X}'
('0xff', 'ff', 'FF')

See also format() for more information.

See also int() for converting a hexadecimal string to an integer using a base of 16.

Note: To obtain a hexadecimal string representation for a float, use the float.hex() method.



id(object)

Description: tbd

Examples:

Ex 0: Documentation

Return the "identity" of an object. This is an integer which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value.

CPython implementation detail: This is the address of the object in memory.

Raises an auditing event builtins.id with argument id.



input([prompt])

Description: tbd

Examples:

Ex 0: Documentation

If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, EOFError is raised. Example:

>>> s = input('--> ')  
--> Monty Python's Flying Circus
>>> s
"Monty Python's Flying Circus"

If the readline module was loaded, then input() will use it to provide elaborate line editing and history features.

Raises an auditing event builtins.input with argument prompt before reading input

Raises an auditing event builtins.input/result with the result after successfully reading input.



int([x]); int(x, base=10)

Description: tbd

Examples:

Ex 0: Documentation

Return an integer object constructed from a number or string x, or return 0 if no arguments are given. If x defines __int__(), int(x) returns x.__int__(). If x defines __index__(), it returns x.__index__(). If x defines __trunc__(), it returns x.__trunc__(). For floating point numbers, this truncates towards zero.

If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in radix base. Optionally, the literal can be preceded by + or - (with no space in between) and surrounded by whitespace. A base-n literal consists of the digits 0 to n-1, with a to z (or A to Z) having values 10 to 35. The default base is 10. The allowed values are 0 and 2–36. Base-2, -8, and -16 literals can be optionally prefixed with 0b/0B, 0o/0O, or 0x/0X, as with integer literals in code. Base 0 means to interpret exactly as a code literal, so that the actual base is 2, 8, 10, or 16, and so that int('010', 0) is not legal, while int('010') is, as well as int('010', 8).

The integer type is described in Numeric Types — int, float, complex.

Changed in version 3.4: If base is not an instance of int and the base object has a base.__index__ method, that method is called to obtain an integer for the base. Previous versions used base.__int__ instead of base.__index__.

Changed in version 3.6: Grouping digits with underscores as in code literals is allowed.

Changed in version 3.7: x is now a positional-only parameter.

Changed in version 3.8: Falls back to __index__() if __int__() is not defined.



isinstance(object, classinfo)

Description: tbd

Examples:

Ex 0: Documentation

Return True if the object argument is an instance of the classinfo argument, or of a (direct, indirect or virtual) subclass thereof. If object is not an object of the given type, the function always returns False. If classinfo is a tuple of type objects (or recursively, other such tuples), return True if object is an instance of any of the types. If classinfo is not a type or tuple of types and such tuples, a TypeError exception is raised.



issubclass(class, classinfo)

Description: tbd

Examples:

Ex 0: Documentation

Return True if class is a subclass (direct, indirect or virtual) of classinfo. A class is considered a subclass of itself. classinfo may be a tuple of class objects, in which case every entry in classinfo will be checked. In any other case, a TypeError exception is raised.



iter(object[, sentinel])

Description: tbd

Examples:

Return an iterator object. The first argument is interpreted very differently depending on the presence of the second argument. Without a second argument, object must be a collection object which supports the iteration protocol (the __iter__() method), or it must support the sequence protocol (the __getitem__() method with integer arguments starting at 0). If it does not support either of those protocols, TypeError is raised. If the second argument, sentinel, is given, then object must be a callable object. The iterator created in this case will call object with no arguments for each call to its __next__() method; if the value returned is equal to sentinel, StopIteration will be raised, otherwise the value will be returned.

See also Iterator Types.

One useful application of the second form of iter() is to build a block-reader. For example, reading fixed-width blocks from a binary database file until the end of file is reached:

from functools import partial
with open('mydata.db', 'rb') as f:
for block in iter(partial(f.read, 64), b''):
process_block(block)

len(s)

Description: tbd

Examples:

Ex 0: Documentation

Return the length (the number of items) of an object. The argument may be a sequence (such as a string, bytes, tuple, list, or range) or a collection (such as a dictionary, set, or frozen set).

CPython implementation detail: len raises OverflowError on lengths larger than sys.maxsize, such as range(2 ** 100).



list([iterable])

Description: tbd

Examples:

Ex 0: Documentation

Rather than being a function, list is actually a mutable sequence type, as documented in Lists and Sequence Types — list, tuple, range.



locals()

Description: tbd

Examples:

Ex 0: Documentation

Update and return a dictionary representing the current local symbol table. Free variables are returned by locals() when it is called in function blocks, but not in class blocks. Note that at the module level, locals() and globals() are the same dictionary.

Note: The contents of this dictionary should not be modified; changes may not affect the values of local and free variables used by the interpreter.



map(function, iterable, ...)

Description: tbd

Examples:

Ex 0: Documentation

Return an iterator that applies function to every item of iterable (e.g., a string, list, tuple, dict, etc.), yielding the results. If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel. With multiple iterables, the iterator stops when the shortest iterable is exhausted. For cases where the function inputs are already arranged into argument tuples, see itertools.starmap().


Ex 1: Basic illustration of usage

The code block

nums = [1,2,3]

def non_lambda(num):
return num ** 2

my_nonlambda_iterator = map(non_lambda, nums)
my_lambda_iterator = map(lambda x: x**2, nums)

print(my_lambda_iterator)
print(next(my_lambda_iterator))
print(next(my_lambda_iterator))
print(next(my_lambda_iterator))

print(my_nonlambda_iterator)
print(list(my_nonlambda_iterator))

has the following output:

<map object at 0x10753bdf0>
1
4
9
<map object at 0x10753be80>
[1, 4, 9]

This illustrates that the map function returns an iterator which can be unpacked all at once by means of something like list or can be iterated through by means of the built-in next function.

As noted in the description for map, this function can take multiple iterables--the iterator stops when the shortest iterable is exhausted.

For example, the code block above can be adjusted to

nums1 = [1,2,3]
nums2 = [4,5,6,7]
nums3 = [8,9,10,11,12]

def non_lambda(num1, num2, num3):
return num1 + num2 + num3

my_nonlambda_iterator = map(non_lambda, nums1, nums2, nums3)
my_lambda_iterator = map(lambda x,y,z: x+y+z, nums1, nums2, nums3)

print(my_lambda_iterator)
print(next(my_lambda_iterator))
print(next(my_lambda_iterator))
print(next(my_lambda_iterator))

print(my_nonlambda_iterator)
print(list(my_nonlambda_iterator))

which will yield the output

<map object at 0x10fbcddf0>
13
16
19
<map object at 0x10fbcdf10>
[13, 16, 19]

In this case, nums1 = [1,2,3] is the shortest iterable.


Ex 2: Converting map object to set
def calculateSquare(n):
return n*n


numbers = (1, 2, 3, 4)
result = map(calculateSquare, numbers)
print(result)

# converting map object to set
numbersSquare = set(result)
print(numbersSquare)

yields

<map object at 0x7f722da129e8>
{16, 1, 4, 9}

Each item of the tuple is squared.


Ex 3: Using a lambda function with map

Since map expects a function to be passed in, lambda functions are commonly used while working with map. A lambda function is a short function without a name (similar to anonymous functions () => {} in JavaScript; the main difference is that lambda functions need to be one-liners in Python).

The code block

numbers = (1, 2, 3, 4)
result = map(lambda x: x*x, numbers)
print(result)

# converting map object to set
numbersSquare = set(result)
print(numbersSquare)

yields as its output:

<map 0x7fafc21ccb00>
{16, 1, 4, 9}

There is no real difference from this example to the one previous.


Ex 4: Passing multiple iterables to map and using lambda

We can add corresponding items of two lists:

num1 = [4, 5, 6]
num2 = [5, 6, 7]

result = map(lambda n1, n2: n1+n2, num1, num2)
print(list(result))

This yields:

[9, 11, 13]

Ex 5: Number to sum of its numerals (Edabit challenge)

From this challenge we see that a number is said to be Harshad if it is exactly divisible by the sum of its digits. Create a function that determines whether a number is Harshad or not.

is_harshad(75) ➞ False
# 7 + 5 = 12
# 75 is not exactly divisible by 12

is_harshad(171) ➞ True
# 1 + 7 + 1 = 9
# 9 exactly divides 171

is_harshad(481) ➞ True

is_harshad(89) ➞ False

is_harshad(516) ➞ True

is_harshad(200) ➞ True

The map function can be used to our advantage here:

def is_harshad(n):
S = sum(map(int, str(n)))
return n % S == 0

By itself, n is not iterable. But strings are iterable. Hence, str(n) gives us an iterable string whose characters are the numerals that make up n. We can use the map function to apply the int function to each character in str(n) to yield an iterator upon which sum can act.



max(iterable, *[, key, default]); max(arg1, arg2, *args[, key])

Description: tbd

Examples:

Ex 0: Documentation

Return the largest item in an iterable or the largest of two or more arguments.

If one positional argument is provided, it should be an iterable. The largest item in the iterable is returned. If two or more positional arguments are provided, the largest of the positional arguments is returned.

There are two optional keyword-only arguments. The key argument specifies a one-argument ordering function like that used for list.sort(). The default argument specifies an object to return if the provided iterable is empty. If the iterable is empty and default is not provided, a ValueError is raised.

If multiple items are maximal, the function returns the first one encountered. This is consistent with other sort-stability preserving tools such as sorted(iterable, key=keyfunc, reverse=True)[0] and heapq.nlargest(1, iterable, key=keyfunc).

New in version 3.4: The default keyword-only argument.

Changed in version 3.8: The key can be None.



memoryview(object)

Description: tbd

Examples:

Ex 0: Documentation

Return a "memory view" object created from the given argument. See Memory Views for more information.



min(iterable, *[, key, default]); min(arg1, arg2, *args[, key])

Description: tbd

Examples:

Ex 0: Documentation

Return the smallest item in an iterable or the smallest of two or more arguments.

If one positional argument is provided, it should be an iterable. The smallest item in the iterable is returned. If two or more positional arguments are provided, the smallest of the positional arguments is returned.

There are two optional keyword-only arguments. The key argument specifies a one-argument ordering function like that used for list.sort(). The default argument specifies an object to return if the provided iterable is empty. If the iterable is empty and default is not provided, a ValueError is raised.

If multiple items are minimal, the function returns the first one encountered. This is consistent with other sort-stability preserving tools such as sorted(iterable, key=keyfunc)[0] and heapq.nsmallest(1, iterable, key=keyfunc).

New in version 3.4: The default keyword-only argument.

Changed in version 3.8: The key can be None.



next(iterator[, default])

Description: tbd

Examples:

Ex 0: Documentation

Retrieve the next item from the iterator by calling its __next__() method. If default is given, it is returned if the iterator is exhausted, otherwise StopIteration is raised.



object()

Description: tbd

Examples:

Return a new featureless object. object is a base for all classes. It has the methods that are common to all instances of Python classes. This function does not accept any arguments.

Note: object does not have a __dict__, so you can't assign arbitrary attributes to an instance of the object class.


oct(x)

Description: tbd

Examples:

Ex 0: Documentation

Convert an integer number to an octal string prefixed with "0o". The result is a valid Python expression. If x is not a Python int object, it has to define an __index__() method that returns an integer. For example:

>>> oct(8)
'0o10'
>>> oct(-56)
'-0o70'

If you want to convert an integer number to octal string either with prefix "0o" or not, you can use either of the following ways.

>>> '%#o' % 10, '%o' % 10
('0o12', '12')
>>> format(10, '#o'), format(10, 'o')
('0o12', '12')
>>> f'{10:#o}', f'{10:o}'
('0o12', '12')

See also format() for more information.


Ascii Table:

ASCII Table
DecHexOctBinaryHTMLCharDescription
00000000000000&#0;NULNull
10100100000001&#1;SOHStart of Header
20200200000010&#2;STXStart of Text
30300300000011&#3;ETXEnd of Text
40400400000100&#4;EOTEnd of Transmission
50500500000101&#5;ENQEnquiry
60600600000110&#6;ACKAcknowledge
70700700000111&#7;BELBell
80801000001000&#8;BSBackspace
90901100001001&#9;HTHorizontal Tab
100A01200001010&#10;LFLine Feed
110B01300001011&#11;VTVertical Tab
120C01400001100&#12;FFForm Feed
130D01500001101&#13;CRCarriage Return
140E01600001110&#14;SOShift Out
150F01700001111&#15;SIShift In
161002000010000&#16;DLEData Link Escape
171102100010001&#17;DC1Device Control 1
181202200010010&#18;DC2Device Control 2
191302300010011&#19;DC3Device Control 3
201402400010100&#20;DC4Device Control 4
211502500010101&#21;NAKNegative Acknowledge
221602600010110&#22;SYNSynchronize
231702700010111&#23;ETBEnd of Transmission Block
241803000011000&#24;CANCancel
251903100011001&#25;EMEnd of Medium
261A03200011010&#26;SUBSubstitute
271B03300011011&#27;ESCEscape
281C03400011100&#28;FSFile Separator
291D03500011101&#29;GSGroup Separator
301E03600011110&#30;RSRecord Separator
311F03700011111&#31;USUnit Separator
322004000100000&#32;spaceSpace
332104100100001&#33;!exclamation mark
342204200100010&#34;"double quote
352304300100011&#35;#number
362404400100100&#36;$dollar
372504500100101&#37;%percent
382604600100110&#38;&ampersand
392704700100111&#39;'single quote
402805000101000&#40;(left parenthesis
412905100101001&#41;)right parenthesis
422A05200101010&#42;*asterisk
432B05300101011&#43;+plus
442C05400101100&#44;,comma
452D05500101101&#45;-minus
462E05600101110&#46;.period
472F05700101111&#47;/slash
483006000110000&#48;0zero
493106100110001&#49;1one
503206200110010&#50;2two
513306300110011&#51;3three
523406400110100&#52;4four
533506500110101&#53;5five
543606600110110&#54;6six
553706700110111&#55;7seven
563807000111000&#56;8eight
573907100111001&#57;9nine
583A07200111010&#58;:colon
593B07300111011&#59;;
603C07400111100&#60;<less than
613D07500111101&#61;=equality sign
623E07600111110&#62;>greater than
633F07700111111&#63;?question mark
644010001000000&#64;@at sign
654110101000001&#65;A
664210201000010&#66;B
674310301000011&#67;C
684410401000100&#68;D
694510501000101&#69;E
704610601000110&#70;F
714710701000111&#71;G
724811001001000&#72;H
734911101001001&#73;I
744A11201001010&#74;J
754B11301001011&#75;K
764C11401001100&#76;L
774D11501001101&#77;M
784E11601001110&#78;N
794F11701001111&#79;O
805012001010000&#80;P
815112101010001&#81;Q
825212201010010&#82;R
835312301010011&#83;S
845412401010100&#84;T
855512501010101&#85;U
865612601010110&#86;V
875712701010111&#87;W
885813001011000&#88;X
895913101011001&#89;Y
905A13201011010&#90;Z
915B13301011011&#91;[left square bracket
925C13401011100&#92;\backslash
935D13501011101&#93;]right square bracket
945E13601011110&#94;^caret / circumflex
955F13701011111&#95;_underscore
966014001100000&#96;`grave / accent
976114101100001&#97;a
986214201100010&#98;b
996314301100011&#99;c
1006414401100100&#100;d
1016514501100101&#101;e
1026614601100110&#102;f
1036714701100111&#103;g
1046815001101000&#104;h
1056915101101001&#105;i
1066A15201101010&#106;j
1076B15301101011&#107;k
1086C15401101100&#108;l
1096D15501101101&#109;m
1106E15601101110&#110;n
1116F15701101111&#111;o
1127016001110000&#112;p
1137116101110001&#113;q
1147216201110010&#114;r
1157316301110011&#115;s
1167416401110100&#116;t
1177516501110101&#117;u
1187616601110110&#118;v
1197716701110111&#119;w
1207817001111000&#120;x
1217917101111001&#121;y
1227A17201111010&#122;z
1237B17301111011&#123;{left curly bracket
1247C17401111100&#124;|vertical bar
1257D17501111101&#125;}right curly bracket
1267E17601111110&#126;~tilde
1277F17701111111&#127;DELdelete

Extended ASCII Table
DecHexBinaryHTMLChar
1288010000000-€
1298110000001-
1308210000010-‚
1318310000011-ƒ
1328410000100-„
1338510000101-…
1348610000110-†
1358710000111-‡
1368810001000-ˆ
1378910001001-‰
1388A10001010-Š
1398B10001011-‹
1408C10001100-Œ
1418D10001101-
1428E10001110-Ž
1438F10001111-
1449010010000-
1459110010001-‘
1469210010010-’
1479310010011-“
1489410010100-”
1499510010101-•
1509610010110-–
1519710010111-—
1529810011000-˜
1539910011001-™
1549A10011010-š
1559B10011011-›
1569C10011100-œ
1579D10011101-
1589E10011110-ž
1599F10011111-Ÿ
160A010100000&#160;
161A110100001&#161;¡
162A210100010&#162;¢
163A310100011&#163;£
164A410100100&#164;¤
165A510100101&#165;¥
166A610100110&#166;¦
167A710100111&#167;§
168A810101000&#168;¨
169A910101001&#169;©
170AA10101010&#170;ª
171AB10101011&#171;«
172AC10101100&#172;¬
173AD10101101&#173;­
174AE10101110&#174;®
175AF10101111&#175;¯
176B010110000&#176;°
177B110110001&#177;±
178B210110010&#178;²
179B310110011&#179;³
180B410110100&#180;´
181B510110101&#181;µ
182B610110110&#182;
183B710110111&#183;·
184B810111000&#184;¸
185B910111001&#185;¹
186BA10111010&#186;º
187BB10111011&#187;»
188BC10111100&#188;¼
189BD10111101&#189;½
190BE10111110&#190;¾
191BF10111111&#191;¿
192C011000000&#192;À
193C111000001&#193;Á
194C211000010&#194;Â
195C311000011&#195;Ã
196C411000100&#196;Ä
197C511000101&#197;Å
198C611000110&#198;Æ
199C711000111&#199;Ç
200C811001000&#200;È
201C911001001&#201;É
202CA11001010&#202;Ê
203CB11001011&#203;Ë
204CC11001100&#204;Ì
205CD11001101&#205;Í
206CE11001110&#206;Î
207CF11001111&#207;Ï
208D011010000&#208;Ð
209D111010001&#209;Ñ
210D211010010&#210;Ò
211D311010011&#211;Ó
212D411010100&#212;Ô
213D511010101&#213;Õ
214D611010110&#214;Ö
215D711010111&#215;×
216D811011000&#216;Ø
217D911011001&#217;Ù
218DA11011010&#218;Ú
219DB11011011&#219;Û
220DC11011100&#220;Ü
221DD11011101&#221;Ý
222DE11011110&#222;Þ
223DF11011111&#223;ß
224E011100000&#224;à
225E111100001&#225;á
226E211100010&#226;â
227E311100011&#227;ã
228E411100100&#228;ä
229E511100101&#229;å
230E611100110&#230;æ
231E711100111&#231;ç
232E811101000&#232;è
233E911101001&#233;é
234EA11101010&#234;ê
235EB11101011&#235;ë
236EC11101100&#236;ì
237ED11101101&#237;í
238EE11101110&#238;î
239EF11101111&#239;ï
240F011110000&#240;ð
241F111110001&#241;ñ
242F211110010&#242;ò
243F311110011&#243;ó
244F411110100&#244;ô
245F511110101&#245;õ
246F611110110&#246;ö
247F711110111&#247;÷
248F811111000&#248;ø
249F911111001&#249;ù
250FA11111010&#250;ú
251FB11111011&#251;û
252FC11111100&#252;ü
253FD11111101&#253;ý
254FE11111110&#254;þ
255FF11111111&#255;ÿ


open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

Description: tbd

Examples:

Ex 0: Documentation

Open file and return a corresponding file object. If the file cannot be opened, an OSError is raised. See Reading and Writing Files for more examples of how to use this function.

file is a path-like object giving the pathname (absolute or relative to the current working directory) of the file to be opened or an integer file descriptor of the file to be wrapped. (If a file descriptor is given, it is closed when the returned I/O object is closed, unless closefd is set to False.)

mode is an optional string that specifies the mode in which the file is opened. It defaults to 'r' which means open for reading in text mode. Other common values are 'w' for writing (truncating the file if it already exists), 'x' for exclusive creation and 'a' for appending (which on some Unix systems, means that all writes append to the end of the file regardless of the current seek position). In text mode, if encoding is not specified the encoding used is platform dependent: locale.getpreferredencoding(False) is called to get the current locale encoding. (For reading and writing raw bytes use binary mode and leave encoding unspecified.) The available modes are:

CharacterMeaning
'r'open for reading (default)
'w'open for writing, truncating the file first
'x'open for exclusive creation, failing if the file already exists
'a'open for writing, appending to the end of the file if it exists
'b'binary mode
't'text mode (default)
'+'open for updating (reading and writing)

The default mode is 'r' (open for reading text, synonym of 'rt'). Modes 'w+' and 'w+b' open and truncate the file. Modes 'r+' and 'r+b' open the file with no truncation.

As mentioned in the Overview, Python distinguishes between binary and text I/O. Files opened in binary mode (including 'b' in the mode argument) return contents as bytes objects without any decoding. In text mode (the default, or when 't' is included in the mode argument), the contents of the file are returned as str, the bytes having been first decoded using a platform-dependent encoding or using the specified encoding if given.

There is an additional mode character permitted, 'U', which no longer has any effect, and is considered deprecated. It previously enabled universal newlines in text mode, which became the default behaviour in Python 3.0. Refer to the documentation of the newline parameter for further details.

Note: Python doesn't depend on the underlying operating system's notion of text files; all the processing is done by Python itself, and is therefore platform-independent.

buffering is an optional integer used to set the buffering policy. Pass 0 to switch buffering off (only allowed in binary mode), 1 to select line buffering (only usable in text mode), and an integer > 1 to indicate the size in bytes of a fixed-size chunk buffer. When no buffering argument is given, the default buffering policy works as follows:

  • Binary files are buffered in fixed-size chunks; the size of the buffer is chosen using a heuristic trying to determine the underlying device's "block size" and falling back on io.DEFAULT_BUFFER_SIZE. On many systems, the buffer will typically be 4096 or 8192 bytes long.
  • "Interactive" text files (files for which isatty() returns True) use line buffering. Other text files use the policy described above for binary files.

encoding is the name of the encoding used to decode or encode the file. This should only be used in text mode. The default encoding is platform dependent (whatever locale.getpreferredencoding() returns), but any text encoding supported by Python can be used. See the codecs module for the list of supported encodings.

errors is an optional string that specifies how encoding and decoding errors are to be handled—this cannot be used in binary mode. A variety of standard error handlers are available (listed under Error Handlers), though any error handling name that has been registered with codecs.register_error() is also valid. The standard names include:

  • 'strict' to raise a ValueError exception if there is an encoding error. The default value of None has the same effect.
  • 'ignore' ignores errors. Note that ignoring encoding errors can lead to data loss.
  • 'replace' causes a replacement marker (such as '?') to be inserted where there is malformed data.
  • 'surrogateescape' will represent any incorrect bytes as low surrogate code units ranging from U+DC80 to U+DCFF. These surrogate code units will then be turned back into the same bytes when the surrogateescape error handler is used when writing data. This is useful for processing files in an unknown encoding.
  • 'xmlcharrefreplace' is only supported when writing to a file. Characters not supported by the encoding are replaced with the appropriate XML character reference &#nnn;.
  • 'backslashreplace' replaces malformed data by Python's backslashed escape sequences.
  • 'namereplace' (also only supported when writing) replaces unsupported characters with \N{...} escape sequences.

newline controls how universal newlines mode works (it only applies to text mode). It can be None, '', '\n', '\r', and '\r\n'. It works as follows:

  • When reading input from the stream, if newline is None, universal newlines mode is enabled. Lines in the input can end in '\n', '\r', or '\r\n', and these are translated into '\n' before being returned to the caller. If it is '', universal newlines mode is enabled, but line endings are returned to the caller untranslated. If it has any of the other legal values, input lines are only terminated by the given string, and the line ending is returned to the caller untranslated.
  • When writing output to the stream, if newline is None, any '\n' characters written are translated to the system default line separator, os.linesep. If newline is '' or '\n', no translation takes place. If newline is any of the other legal values, any '\n' characters written are translated to the given string.

If closefd is False and a file descriptor rather than a filename was given, the underlying file descriptor will be kept open when the file is closed. If a filename is given closefd must be True (the default) otherwise an error will be raised.

A custom opener can be used by passing a callable as opener. The underlying file descriptor for the file object is then obtained by calling opener with (file, flags). opener must return an open file descriptor (passing os.open() as opener results in functionality similar to passing None).

The newly created file is non-inheritable.

The following example uses the dir_fd parameter of the os.open() function to open a file relative to a given directory:

>>> import os
>>> dir_fd = os.open('somedir', os.O_RDONLY)
>>> def opener(path, flags):
... return os.open(path, flags, dir_fd=dir_fd)
...
>>> with open('spamspam.txt', 'w', opener=opener) as f:
... print('This will be written to somedir/spamspam.txt', file=f)
...
>>> os.close(dir_fd) # don't leak a file descriptor

The type of file object returned by the open() function depends on the mode. When open() is used to open a file in a text mode ('w', 'r', 'wt', 'rt', etc.), it returns a subclass of io.TextIOBase (specifically io.TextIOWrapper). When used to open a file in a binary mode with buffering, the returned class is a subclass of io.BufferedIOBase. The exact class varies: in read binary mode, it returns an io.BufferedReader; in write binary and append binary modes, it returns an io.BufferedWriter, and in read/write mode, it returns an io.BufferedRandom. When buffering is disabled, the raw stream, a subclass of io.RawIOBase, io.FileIO, is returned.

See also the file handling modules, such as, fileinput, io (where open() is declared), os, os.path, tempfile, and shutil.

Raises an auditing event open with arguments file, mode, flags.

The mode and flags arguments may have been modified or inferred from the original call.

Changed in version 3.3:

  • The opener parameter was added.
  • The 'x' mode was added.
  • IOError used to be raised, it is now an alias of OSError.
  • FileExistsError is now raised if the file opened in exclusive creation mode ('x') already exists.

Changed in version 3.4:

  • The file is now non-inheritable.

Deprecated since version 3.4, will be removed in version 3.10: The 'U' mode.

Changed in version 3.5:

  • If the system call is interrupted and the signal handler does not raise an exception, the function now retries the system call instead of raising an InterruptedError exception (see PEP 475 for the rationale).
  • The 'namereplace' error handler was added.

Changed in version 3.6:



ord(c)

Description: tbd

Examples:

Ex 0: Documentation

Given a string representing one Unicode character, return an integer representing the Unicode code point of that character. For example, ord('a') returns the integer 97 and ord('€') (Euro sign) returns 8364. This is the inverse of chr().


Ascii Table:

ASCII Table
DecHexOctBinaryHTMLCharDescription
00000000000000&#0;NULNull
10100100000001&#1;SOHStart of Header
20200200000010&#2;STXStart of Text
30300300000011&#3;ETXEnd of Text
40400400000100&#4;EOTEnd of Transmission
50500500000101&#5;ENQEnquiry
60600600000110&#6;ACKAcknowledge
70700700000111&#7;BELBell
80801000001000&#8;BSBackspace
90901100001001&#9;HTHorizontal Tab
100A01200001010&#10;LFLine Feed
110B01300001011&#11;VTVertical Tab
120C01400001100&#12;FFForm Feed
130D01500001101&#13;CRCarriage Return
140E01600001110&#14;SOShift Out
150F01700001111&#15;SIShift In
161002000010000&#16;DLEData Link Escape
171102100010001&#17;DC1Device Control 1
181202200010010&#18;DC2Device Control 2
191302300010011&#19;DC3Device Control 3
201402400010100&#20;DC4Device Control 4
211502500010101&#21;NAKNegative Acknowledge
221602600010110&#22;SYNSynchronize
231702700010111&#23;ETBEnd of Transmission Block
241803000011000&#24;CANCancel
251903100011001&#25;EMEnd of Medium
261A03200011010&#26;SUBSubstitute
271B03300011011&#27;ESCEscape
281C03400011100&#28;FSFile Separator
291D03500011101&#29;GSGroup Separator
301E03600011110&#30;RSRecord Separator
311F03700011111&#31;USUnit Separator
322004000100000&#32;spaceSpace
332104100100001&#33;!exclamation mark
342204200100010&#34;"double quote
352304300100011&#35;#number
362404400100100&#36;$dollar
372504500100101&#37;%percent
382604600100110&#38;&ampersand
392704700100111&#39;'single quote
402805000101000&#40;(left parenthesis
412905100101001&#41;)right parenthesis
422A05200101010&#42;*asterisk
432B05300101011&#43;+plus
442C05400101100&#44;,comma
452D05500101101&#45;-minus
462E05600101110&#46;.period
472F05700101111&#47;/slash
483006000110000&#48;0zero
493106100110001&#49;1one
503206200110010&#50;2two
513306300110011&#51;3three
523406400110100&#52;4four
533506500110101&#53;5five
543606600110110&#54;6six
553706700110111&#55;7seven
563807000111000&#56;8eight
573907100111001&#57;9nine
583A07200111010&#58;:colon
593B07300111011&#59;;
603C07400111100&#60;<less than
613D07500111101&#61;=equality sign
623E07600111110&#62;>greater than
633F07700111111&#63;?question mark
644010001000000&#64;@at sign
654110101000001&#65;A
664210201000010&#66;B
674310301000011&#67;C
684410401000100&#68;D
694510501000101&#69;E
704610601000110&#70;F
714710701000111&#71;G
724811001001000&#72;H
734911101001001&#73;I
744A11201001010&#74;J
754B11301001011&#75;K
764C11401001100&#76;L
774D11501001101&#77;M
784E11601001110&#78;N
794F11701001111&#79;O
805012001010000&#80;P
815112101010001&#81;Q
825212201010010&#82;R
835312301010011&#83;S
845412401010100&#84;T
855512501010101&#85;U
865612601010110&#86;V
875712701010111&#87;W
885813001011000&#88;X
895913101011001&#89;Y
905A13201011010&#90;Z
915B13301011011&#91;[left square bracket
925C13401011100&#92;\backslash
935D13501011101&#93;]right square bracket
945E13601011110&#94;^caret / circumflex
955F13701011111&#95;_underscore
966014001100000&#96;`grave / accent
976114101100001&#97;a
986214201100010&#98;b
996314301100011&#99;c
1006414401100100&#100;d
1016514501100101&#101;e
1026614601100110&#102;f
1036714701100111&#103;g
1046815001101000&#104;h
1056915101101001&#105;i
1066A15201101010&#106;j
1076B15301101011&#107;k
1086C15401101100&#108;l
1096D15501101101&#109;m
1106E15601101110&#110;n
1116F15701101111&#111;o
1127016001110000&#112;p
1137116101110001&#113;q
1147216201110010&#114;r
1157316301110011&#115;s
1167416401110100&#116;t
1177516501110101&#117;u
1187616601110110&#118;v
1197716701110111&#119;w
1207817001111000&#120;x
1217917101111001&#121;y
1227A17201111010&#122;z
1237B17301111011&#123;{left curly bracket
1247C17401111100&#124;|vertical bar
1257D17501111101&#125;}right curly bracket
1267E17601111110&#126;~tilde
1277F17701111111&#127;DELdelete

Extended ASCII Table
DecHexBinaryHTMLChar
1288010000000-€
1298110000001-
1308210000010-‚
1318310000011-ƒ
1328410000100-„
1338510000101-…
1348610000110-†
1358710000111-‡
1368810001000-ˆ
1378910001001-‰
1388A10001010-Š
1398B10001011-‹
1408C10001100-Œ
1418D10001101-
1428E10001110-Ž
1438F10001111-
1449010010000-
1459110010001-‘
1469210010010-’
1479310010011-“
1489410010100-”
1499510010101-•
1509610010110-–
1519710010111-—
1529810011000-˜
1539910011001-™
1549A10011010-š
1559B10011011-›
1569C10011100-œ
1579D10011101-
1589E10011110-ž
1599F10011111-Ÿ
160A010100000&#160;
161A110100001&#161;¡
162A210100010&#162;¢
163A310100011&#163;£
164A410100100&#164;¤
165A510100101&#165;¥
166A610100110&#166;¦
167A710100111&#167;§
168A810101000&#168;¨
169A910101001&#169;©
170AA10101010&#170;ª
171AB10101011&#171;«
172AC10101100&#172;¬
173AD10101101&#173;­
174AE10101110&#174;®
175AF10101111&#175;¯
176B010110000&#176;°
177B110110001&#177;±
178B210110010&#178;²
179B310110011&#179;³
180B410110100&#180;´
181B510110101&#181;µ
182B610110110&#182;
183B710110111&#183;·
184B810111000&#184;¸
185B910111001&#185;¹
186BA10111010&#186;º
187BB10111011&#187;»
188BC10111100&#188;¼
189BD10111101&#189;½
190BE10111110&#190;¾
191BF10111111&#191;¿
192C011000000&#192;À
193C111000001&#193;Á
194C211000010&#194;Â
195C311000011&#195;Ã
196C411000100&#196;Ä
197C511000101&#197;Å
198C611000110&#198;Æ
199C711000111&#199;Ç
200C811001000&#200;È
201C911001001&#201;É
202CA11001010&#202;Ê
203CB11001011&#203;Ë
204CC11001100&#204;Ì
205CD11001101&#205;Í
206CE11001110&#206;Î
207CF11001111&#207;Ï
208D011010000&#208;Ð
209D111010001&#209;Ñ
210D211010010&#210;Ò
211D311010011&#211;Ó
212D411010100&#212;Ô
213D511010101&#213;Õ
214D611010110&#214;Ö
215D711010111&#215;×
216D811011000&#216;Ø
217D911011001&#217;Ù
218DA11011010&#218;Ú
219DB11011011&#219;Û
220DC11011100&#220;Ü
221DD11011101&#221;Ý
222DE11011110&#222;Þ
223DF11011111&#223;ß
224E011100000&#224;à
225E111100001&#225;á
226E211100010&#226;â
227E311100011&#227;ã
228E411100100&#228;ä
229E511100101&#229;å
230E611100110&#230;æ
231E711100111&#231;ç
232E811101000&#232;è
233E911101001&#233;é
234EA11101010&#234;ê
235EB11101011&#235;ë
236EC11101100&#236;ì
237ED11101101&#237;í
238EE11101110&#238;î
239EF11101111&#239;ï
240F011110000&#240;ð
241F111110001&#241;ñ
242F211110010&#242;ò
243F311110011&#243;ó
244F411110100&#244;ô
245F511110101&#245;õ
246F611110110&#246;ö
247F711110111&#247;÷
248F811111000&#248;ø
249F911111001&#249;ù
250FA11111010&#250;ú
251FB11111011&#251;û
252FC11111100&#252;ü
253FD11111101&#253;ý
254FE11111110&#254;þ
255FF11111111&#255;ÿ


pow(base, exp[, mod])

Description: tbd

Examples:

Ex 0: Documentation

Return base to the power exp; if mod is present, return base to the power exp, modulo mod (computed more efficiently than pow(base, exp) % mod). The two-argument form pow(base, exp) is equivalent to using the power operator: base**exp.

The arguments must have numeric types. With mixed operand types, the coercion rules for binary arithmetic operators apply. For int operands, the result has the same type as the operands (after coercion) unless the second argument is negative; in that case, all arguments are converted to float and a float result is delivered. For example, 10**2 returns 100, but 10**-2 returns 0.01.

For int operands base and exp, if mod is present, mod must also be of integer type and mod must be nonzero. If mod is present and exp is negative, base must be relatively prime to mod. In that case, pow(inv_base, -exp, mod) is returned, where inv_base is an inverse to base modulo mod.

Here's an example of computing an inverse for 38 modulo 97:

>>> pow(38, -1, mod=97)
23
>>> 23 * 38 % 97 == 1
True

Changed in version 3.8: For int operands, the three-argument form of pow now allows the second argument to be negative, permitting computation of modular inverses.

Changed in version 3.8: Allow keyword arguments. Formerly, only positional arguments were supported.



print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

Description: tbd

Examples:

Ex 0: Documentation

Print objects to the text stream file, separated by sep and followed by end. sep, end, file and flush, if present, must be given as keyword arguments.

All non-keyword arguments are converted to strings like str() does and written to the stream, separated by sep and followed by end. Both sep and end must be strings; they can also be None, which means to use the default values. If no objects are given, print() will just write end.

The file argument must be an object with a write(string) method; if it is not present or None, sys.stdout will be used. Since printed arguments are converted to text strings, print() cannot be used with binary mode file objects. For these, use file.write(...) instead.

Whether output is buffered is usually determined by file, but if the flush keyword argument is true, the stream is forcibly flushed.

Changed in version 3.3: Added the flush keyword argument.



property(fget=None, fset=None, fdel=None, doc=None)

Description: tbd

Examples:

Ex 0: Documentation

Return a property attribute.

fget is a function for getting an attribute value. fset is a function for setting an attribute value. fdel is a function for deleting an attribute value. And doc creates a docstring for the attribute.

A typical use is to define a managed attribute x:

class C:
def __init__(self):
self._x = None

def getx(self):
return self._x

def setx(self, value):
self._x = value

def delx(self):
del self._x

x = property(getx, setx, delx, "I'm the 'x' property.")

If c is an instance of C, c.x will invoke the getter, c.x = value will invoke the setter and del c.x the deleter.

If given, doc will be the docstring of the property attribute. Otherwise, the property will copy fget's docstring (if it exists). This makes it possible to create read-only properties easily using property() as a decorator:

class Parrot:
def __init__(self):
self._voltage = 100000

@property
def voltage(self):
"""Get the current voltage."""
return self._voltage

The @property decorator turns the voltage() method into a "getter" for a read-only attribute with the same name, and it sets the docstring for voltage to "Get the current voltage."

A property object has getter, setter, and deleter methods usable as decorators that create a copy of the property with the corresponding accessor function set to the decorated function. This is best explained with an example:

class C:
def __init__(self):
self._x = None

@property
def x(self):
"""I'm the 'x' property."""
return self._x

@x.setter
def x(self, value):
self._x = value

@x.deleter
def x(self):
del self._x

This code is exactly equivalent to the first example. Be sure to give the additional functions the same name as the original property (x in this case.)

The returned property object also has the attributes fget, fset, and fdel corresponding to the constructor arguments.

Changed in version 3.5: The docstrings of property objects are now writeable.



range(stop); range(start, stop[, step])

Description: tbd

Examples:

Ex 0: Documentation

Rather than being a function, range is actually an immutable sequence type, as documented in Ranges and Sequence Types — list, tuple, range.



repr(object)

Description: tbd

Examples:

Ex 0: Documentation

Return a string containing a printable representation of an object. For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval(), otherwise the representation is a string enclosed in angle brackets that contains the name of the type of the object together with additional information often including the name and address of the object. A class can control what this function returns for its instances by defining a __repr__() method.



reversed(seq)

Description: tbd

Examples:

Ex 0: Documentation

Return a reverse iterator. seq must be an object which has a __reversed__() method or supports the sequence protocol (the __len__() method and the __getitem__() method with integer arguments starting at 0).



round(number[, ndigits])

Description: tbd

Examples:

Return number rounded to ndigits precision after the decimal point. If ndigits is omitted or is None, it returns the nearest integer to its input.

For the built-in types supporting round(), values are rounded to the closest multiple of 10 to the power minus ndigits; if two multiples are equally close, rounding is done toward the even choice (so, for example, both round(0.5) and round(-0.5) are 0, and round(1.5) is 2). Any integer value is valid for ndigits (positive, zero, or negative). The return value is an integer if ndigits is omitted or None. Otherwise the return value has the same type as number.

For a general Python object number, round delegates to number.__round__.

Note: The behavior of round() for floats can be surprising: for example, round(2.675, 2) gives 2.67 instead of the expected 2.68. This is not a bug: it's a result of the fact that most decimal fractions can't be represented exactly as a float. See Floating Point Arithmetic: Issues and Limitations for more information.


set([iterable])

Description: tbd

Examples:

Ex 0: Documentation

Return a new set object, optionally with elements taken from iterable. set is a built-in class. See set and Set Types — set, frozenset for documentation about this class.

For other containers see the built-in frozenset, list, tuple, and dict classes, as well as the collections module.



setattr(object, name, value)

Description: tbd

Examples:

Ex 0: Documentation

This is the counterpart of getattr(). The arguments are an object, a string and an arbitrary value. The string may name an existing attribute or a new attribute. The function assigns the value to the attribute, provided the object allows it. For example, setattr(x, 'foobar', 123) is equivalent to x.foobar = 123.

Note: Since private name mangling happens at compilation time, one must manually mangle a private attribute's (attributes with two leading underscores) name in order to set it with setattr().



slice(stop); slice(start, stop[, step])

Description: tbd

Examples:

Ex 0: Documentation

Return a slice object representing the set of indices specified by range(start, stop, step). The start and step arguments default to None. Slice objects have read-only data attributes start, stop and step which merely return the argument values (or their default). They have no other explicit functionality; however they are used by Numerical Python and other third party extensions. Slice objects are also generated when extended indexing syntax is used. For example: a[start:stop:step] or a[start:stop, i]. See itertools.islice() for an alternate version that returns an iterator.



sorted(iterable, *, key=None, reverse=False)

Description: tbd

Examples:

Ex 0: Documentation

Return a new sorted list from the items in iterable.

Has two optional arguments which must be specified as keyword arguments.

key specifies a function of one argument that is used to extract a comparison key from each element in iterable (for example, key=str.lower). The default value is None (compare the elements directly).

reverse is a boolean value. If set to True, then the list elements are sorted as if each comparison were reversed.

Use functools.cmp_to_key() to convert an old-style cmp function to a key function.

The built-in sorted() function 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).

For sorting examples and a brief sorting tutorial, see Sorting HOW TO.



@staticmethod

Description: tbd

Examples:

Ex 0: Documentation

Transform a method into a static method.

A static method does not receive an implicit first argument. To declare a static method, use this idiom:

class C:
@staticmethod
def f(arg1, arg2, ...): ...

The @staticmethod form is a function decorator – see Function definitions for details.

A static method can be called either on the class (such as C.f()) or on an instance (such as C().f()).

Static methods in Python are similar to those found in Java or C++. Also see classmethod() for a variant that is useful for creating alternate class constructors.

Like all decorators, it is also possible to call staticmethod as a regular function and do something with its result. This is needed in some cases where you need a reference to a function from a class body and you want to avoid the automatic transformation to instance method. For these cases, use this idiom:

class C:
builtin_open = staticmethod(open)

For more information on static methods, see The standard type hierarchy.



str(object=''); str(object=b'', encoding='utf-8', errors='strict')

Description: tbd

Examples:

Ex 0: Documentation

Return a str version of object. See str() for details.

str is the built-in string class. For general information about strings, see Text Sequence Type — str.



sum(iterable, /, start=0)

Description: tbd

Examples:

Ex 0: Documentation

Sums start and the items of an iterable from left to right and returns the total. The iterable's items are normally numbers, and the start value is not allowed to be a string.

For some use cases, there are good alternatives to sum(). The preferred, fast way to concatenate a sequence of strings is by calling ''.join(sequence). To add floating point values with extended precision, see math.fsum(). To concatenate a series of iterables, consider using itertools.chain().

Changed in version 3.8: The start parameter can be specified as a keyword argument.



super([type[, object-or-type]])

Description: tbd

Examples:

Ex 0: Documentation

Return a proxy object that delegates method calls to a parent or sibling class of type. This is useful for accessing inherited methods that have been overridden in a class.

The object-or-type determines the method resolution order to be searched. The search starts from the class right after the type.

For example, if __mro__ of object-or-type is D -> B -> C -> A -> object and the value of type is B, then super() searches C -> A -> object.

The __mro__ attribute of the object-or-type lists the method resolution search order used by both getattr() and super(). The attribute is dynamic and can change whenever the inheritance hierarchy is updated.

If the second argument is omitted, the super object returned is unbound. If the second argument is an object, isinstance(obj, type) must be true. If the second argument is a type, issubclass(type2, type) must be true (this is useful for classmethods).

There are two typical use cases for super. In a class hierarchy with single inheritance, super can be used to refer to parent classes without naming them explicitly, thus making the code more maintainable. This use closely parallels the use of super in other programming languages.

The second use case is to support cooperative multiple inheritance in a dynamic execution environment. This use case is unique to Python and is not found in statically compiled languages or languages that only support single inheritance. This makes it possible to implement "diamond diagrams" where multiple base classes implement the same method. Good design dictates that such implementations have the same calling signature in every case (because the order of calls is determined at runtime, because that order adapts to changes in the class hierarchy, and because that order can include sibling classes that are unknown prior to runtime).

For both use cases, a typical superclass call looks like this:

class C(B):
def method(self, arg):
super().method(arg) # This does the same thing as:
# super(C, self).method(arg)

In addition to method lookups, super() also works for attribute lookups. One possible use case for this is calling descriptors in a parent or sibling class.

Note that super() is implemented as part of the binding process for explicit dotted attribute lookups such as super().__getitem__(name). It does so by implementing its own __getattribute__() method for searching classes in a predictable order that supports cooperative multiple inheritance. Accordingly, super() is undefined for implicit lookups using statements or operators such as super()[name].

Also note that, aside from the zero argument form, super() is not limited to use inside methods. The two argument form specifies the arguments exactly and makes the appropriate references. The zero argument form only works inside a class definition, as the compiler fills in the necessary details to correctly retrieve the class being defined, as well as accessing the current instance for ordinary methods.

For practical suggestions on how to design cooperative classes using super(), see guide to using super().



tuple([iterable])

Description: tbd

Examples:

Ex 0: Documentation

Rather than being a function, tuple is actually an immutable sequence type, as documented in Tuples and Sequence Types — list, tuple, range.



type(object); type(name, bases, dict, **kwds)

Description: tbd

Examples:

Ex 0: Documentation

With one argument, return the type of an object. The return value is a type object and generally the same object as returned by object.__class__.

The isinstance() built-in function is recommended for testing the type of an object, because it takes subclasses into account.

With three arguments, return a new type object. This is essentially a dynamic form of the class statement. The name string is the class name and becomes the __name__ attribute. The bases tuple contains the base classes and becomes the __bases__ attribute; if empty, object, the ultimate base of all classes, is added. The dict dictionary contains attribute and method definitions for the class body; it may be copied or wrapped before becoming the __dict__ attribute. The following two statements create identical type objects:

>>> class X:
... a = 1
...
>>> X = type('X', (), dict(a=1))

See also Type Objects.

Keyword arguments provided to the three argument form are passed to the appropriate metaclass machinery (usually __init_subclass__()) in the same way that keywords in a class definition (besides metaclass) would.

See also Customizing class creation.

Changed in version 3.6: Subclasses of type which don't override type.__new__ may no longer use the one-argument form to get the type of an object.



vars([object])

Description: tbd

Examples:

Ex 0: Documentation

Return the __dict__ attribute for a module, class, instance, or any other object with a __dict__ attribute.

Objects such as modules and instances have an updateable __dict__ attribute; however, other objects may have write restrictions on their __dict__ attributes (for example, classes use a types.MappingProxyType to prevent direct dictionary updates).

Without an argument, vars() acts like locals(). Note, the locals dictionary is only useful for reads since updates to the locals dictionary are ignored.

A TypeError exception is raised if an object is specified but it doesn't have a __dict__ attribute (for example, if its class defines the __slots__ attribute).



zip(*iterables)

Description: tbd

Examples:

Ex 0: Documentation

Make an iterator that aggregates elements from each of the iterables.

Returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. The iterator stops when the shortest input iterable is exhausted. With a single iterable argument, it returns an iterator of 1-tuples. With no arguments, it returns an empty iterator. Equivalent to:

def zip(*iterables):
# zip('ABCD', 'xy') --> Ax By
sentinel = object()
iterators = [iter(it) for it in iterables]
while iterators:
result = []
for it in iterators:
elem = next(it, sentinel)
if elem is sentinel:
return
result.append(elem)
yield tuple(result)

The left-to-right evaluation order of the iterables is guaranteed. This makes possible an idiom for clustering a data series into n-length groups using zip(*[iter(s)]*n). This repeats the same iterator n times so that each output tuple has the result of n calls to the iterator. This has the effect of dividing the input into n-length chunks.

zip() should only be used with unequal length inputs when you don't care about trailing, unmatched values from the longer iterables. If those values are important, use itertools.zip_longest() instead.

zip() in conjunction with the * operator can be used to unzip a list:

>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> zipped = zip(x, y)
>>> list(zipped)
[(1, 4), (2, 5), (3, 6)]
>>> x2, y2 = zip(*zip(x, y))
>>> x == list(x2) and y == list(y2)
True


__import__(name, globals=None, locals=None, fromlist=(), level=0)

Description: tbd

Examples:

Ex 0: Documentation

Note: This is an advanced function that is not needed in everyday Python programming, unlike importlib.import_module().

This function is invoked by the import statement. It can be replaced (by importing the builtins module and assigning to builtins.__import__) in order to change semantics of the import statement, but doing so is strongly discouraged as it is usually simpler to use import hooks (see PEP 302) to attain the same goals and does not cause issues with code which assumes the default import implementation is in use. Direct use of __import__() is also discouraged in favor of importlib.import_module().

The function imports the module name, potentially using the given globals and locals to determine how to interpret the name in a package context. The fromlist gives the names of objects or submodules that should be imported from the module given by name. The standard implementation does not use its locals argument at all, and uses its globals only to determine the package context of the import statement.

level specifies whether to use absolute or relative imports. 0 (the default) means only perform absolute imports. Positive values for level indicate the number of parent directories to search relative to the directory of the module calling __import__() (see PEP 328 for the details).

When the name variable is of the form package.module, normally, the top-level package (the name up till the first dot) is returned, not the module named by name. However, when a non-empty fromlist argument is given, the module named by name is returned.

For example, the statement import spam results in bytecode resembling the following code:

spam = __import__('spam', globals(), locals(), [], 0)

The statement import spam.ham results in this call:

spam = __import__('spam.ham', globals(), locals(), [], 0)

Note how __import__() returns the toplevel module here because this is the object that is bound to a name by the import statement.

On the other hand, the statement from spam.ham import eggs, sausage as saus results in

_temp = __import__('spam.ham', globals(), locals(), ['eggs', 'sausage'], 0)
eggs = _temp.eggs
saus = _temp.sausage

Here, the spam.ham module is returned from __import__(). From this object, the names to import are retrieved and assigned to their respective names.

If you simply want to import a module (potentially within a package) by name, use importlib.import_module().

Changed in version 3.3: Negative values for level are no longer supported (which also changes the default value to 0).

Changed in version 3.9: When the command line options -E or -I are being used, the environment variable PYTHONCASEOK is now ignored.



String Methods

capitalize()

Description: tbd

Examples:

Ex 0: Documentation

Return a copy of the string with its first character capitalized and the rest lowercased.

Changed in version 3.8: The first character is now put into titlecase rather than uppercase. This means that characters like digraphs will only have their first letter capitalized, instead of the full character.



casefold()

Description: tbd

Examples:

Ex 0: Documentation

Return a casefolded copy of the string. Casefolded strings may be used for caseless matching.

Casefolding is similar to lowercasing but more aggressive because it is intended to remove all case distinctions in a string. For example, the German lowercase letter 'ß' is equivalent to "ss". Since it is already lowercase, lower() would do nothing to 'ß'; casefold() converts it to "ss".

The casefolding algorithm is described in section 3.13 of the Unicode Standard.

New in version 3.3.



center(width[, fillchar])

Description: tbd

Examples:

Ex 0: Documentation

Return centered in a string of length width. Padding is done using the specified fillchar (default is an ASCII space). The original string is returned if width is less than or equal to len(s).



count(sub[, start[, end]])

Description: tbd

Examples:

Ex 0: Documentation

Return the number of non-overlapping occurrences of substring sub in the range [start, end]. Optional arguments start and end are interpreted as in slice notation.



encode(encoding="utf-8", errors="strict")

Description: tbd

Examples:

Ex 0: Documentation

Return an encoded version of the string as a bytes object. Default encoding is 'utf-8'. errors may be given to set a different error handling scheme. The default for errors is 'strict', meaning that encoding errors raise a UnicodeError. Other possible values are 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' and any other name registered via codecs.register_error(), see section Error Handlers. For a list of possible encodings, see section Standard Encodings.

By default, the errors argument is not checked for best performances, but only used at the first encoding error. Enable the Python Development Mode, or use a debug build to check errors.

Changed in version 3.1: Support for keyword arguments added.

Changed in version 3.9: The errors is now checked in development mode and in debug mode.



endswith(suffix[, start[, end]])

Description: tbd

Examples:

Ex 0: Documentation

Return True if the string ends with the specified suffix, otherwise return False. suffix can also be a tuple of suffixes to look for. With optional start, test beginning at that position. With optional end, stop comparing at that position.



expandtabs(tabsize=8)

Description: tbd

Examples:

Ex 0: Documentation

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 tabsize 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 (\t), 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 (\n) or return (\r), 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.

>>> '01\t012\t0123\t01234'.expandtabs()
'01 012 0123 01234'
>>> '01\t012\t0123\t01234'.expandtabs(4)
'01 012 0123 01234'


find(sub[, start[, end]])

Description: tbd

Examples:

Ex 0: Documentation

Return the lowest index in the string where substring sub is found within the slice s[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 if sub is not found.

Note: The find() method should be used only if you need to know the position of sub. To check if sub is a substring or not, use the in operator:

>>> 'Py' in 'Python'
True


format(*args, **kwargs)
Syntax details for formatting expressions (using %) as well as the explicit format method
  • Formatting expression syntax:

    %[(keyname)][flags][width][.prec]typecode
  • String formatting method syntax: Substitution targets in strings used for format method calls take the following general form, all four parts of which are optional, and must appear without intervening spaces (used here for clarity):

    {fieldname component !conversionflag :formatspec}

    The nested formatspec component after the colon character has a syntax of its own, formally described as follows (brackets in this denote optional components and are not coded literally):

    [[fill]align][sign][#][0][width][,][.prec][typecode]
  • f-strings: See the Python docs for more about formatted string literals or so-called "f-strings" for short. Here is a more detailed reference.


Description: Formats the given string. The syntax for the format() string method is

template.format(p0, p1, ..., k0=v0, k1=v1, ...)

where p0, p1, ... are positional arguments, k0, k1, ... are keyword arguments (with values v0, v1, ..., respectively), and template is a string comprised of a mixture of format codes with placeholders for the arguments.

Parameters: The format() method will take any number of parameters, but the type of parameters provided matters:

  • Positional parameters: List of parameters that can be accessed with index of parameter inside curly braces {index}. (Or the index can be omitted entirely and empty braces {} in the template will be substituted for by the order of the positional arguments supplied to format().)
  • Keyword parameters: List of parameters of type key=value, that can be accessed with key of parameter inside curly braces {key}.

Formatting method syntax: The following details are adapted from [2]. Substitution targets in strings used for format method calls take the following general form, all four parts of which are optional, and must appear without intervening spaces (used here for clarity):

{fieldname component !conversionflag :formatspec}

In this substitution target syntax:

  • fieldname

    An optional number or keyword identifying an argument, which may be omitted to use relative argument numbering in 2.7, 3.1, and later.

  • component

    A string of zero or more .name or [index] references used to fetch attributes and indexed values of the argument, which may be omitted to use the whole argument value.

  • conversionflag

    Introduced by a ! if present, which is followed by r, s, or a to call repr(), str(), or ascii() built-in functions on the value, respectively.

  • formatspec

    Introduced by a : if present, and consists of text that specifies how the value should be presented, including details such as field width, alignment, padding, decimal precision, and so on, and ending with an optional datatype code.

The nested formatspec component after the colon character has a syntax of its own, formally described as follows (brackets in this denote optional components and are not coded literally):

[[fill]align][sign][#][0][width][,][.prec][typecode]

In this formatspec nested syntax:

  • fill

    Can be any fill character other than { or }.

  • align

    May be <, >, =, or ^, for left alignment, right alignment, padding after a sign character, or centered alignment, respectively.

  • sign

    May be +, , or space.

  • , (comma)

    Requests a comma for a thousands separator as of Python 3.1 and 2.7.

width and prec

Much as in the % expression (i.e., width for total minimum field width where * can be used to fetch from values and prec for the number of digits or precision to include after the decimal point . where * can be used to fetch from values), and the formatspec may also contain nested {} format strings having a fieldname only, to take values from the arguments list dynamically (much like the * in formatting expressions). A 0 preceding width enables sign-aware zero padding (similar to fill), and a # enables an alternative conversion (if available).

typecode

Largely the same as in % expressions (type codes provided in table below), but the format method has an extra b type code used to give integers in binary format (much like using the bin built-in); has an extra % type code to format percentages as of Python 3.1 and 2.7; and uses only d for base-10 integers (i or u are not used).

Note that unlike the expression's generic %s, the method's s type code requires a string object argument; omit the type code to accept any type generically in the method.

Format type codes for formatting numbers: You can format numbers using the format specifier given below:

TypeMeaning
dDisplays int as a decimal integer
fDisplays float as a fixed point number (Default: 6)
FSame as 'f'. Except displays 'inf' as 'INF' and 'nan' as 'NAN'
gGeneral format. Rounds number to p significant digits. (Default precision: 6)
GSame as 'g'. Except switches to 'E' if the number is large.
%Percentage. Multiples by 100 and puts % at the end.
sString format. This is the default type for strings and may be omitted.
cCorresponding Unicode character
bBinary format
oOctal format
xHexadecimal format (lower case)
XHexadecimal format (upper case)
nSame as 'd'. Except it uses current locale setting for number separator
eExponential notation. (lowercase e)
EExponential notation (uppercase E)

Format type codes for formatting numbers with alignment: The operators <, ^, > and = are used for alignment when assigned a certain width to the numbers.

TypeMeaning
<Left aligned to the remaining space
^Center aligned to the remaining space
>Right aligned to the remaining space
=Forces the signed (+) (-) to the leftmost position

Examples: The format() string method reads the types of arguments passed to format and formats the template string according to the format codes used within the template string. The return value is the formatted string.

Ex 0a: Documentation

Perform a string formatting operation. The string on which this method is called can contain literal text or replacement fields delimited by braces {}. 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.

>>> "The sum of 1 + 2 is {0}".format(1+2)
'The sum of 1 + 2 is 3'

See Format String Syntax for a description of the various formatting options that can be specified in format strings.

Note: When formatting a number (int, float, complex, decimal.Decimal and subclasses) with the n type (ex: '{:n}'.format(1234)), the function temporarily sets the LC_CTYPE locale to the LC_NUMERIC locale to decode decimal_point and thousands_sep fields of localeconv() if they are non-ASCII or longer than 1 byte, and the LC_NUMERIC locale is different than the LC_CTYPE locale. This temporary change affects other threads.

Changed in version 3.7: When formatting a number with the n type, the function sets temporarily the LC_CTYPE locale to the LC_NUMERIC locale in some cases.


Ex 0b: Examples from the official docs

Accessing arguments by position:

>>> '{0}, {1}, {2}'.format('a', 'b', 'c')
'a, b, c'
>>> '{}, {}, {}'.format('a', 'b', 'c') # 3.1+ only
'a, b, c'
>>> '{2}, {1}, {0}'.format('a', 'b', 'c')
'c, b, a'
>>> '{2}, {1}, {0}'.format(*'abc') # unpacking argument sequence
'c, b, a'
>>> '{0}{1}{0}'.format('abra', 'cad') # arguments' indices can be repeated
'abracadabra'

Accessing arguments by name:

>>> 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W')
'Coordinates: 37.24N, -115.81W'
>>> coord = {'latitude': '37.24N', 'longitude': '-115.81W'}
>>> 'Coordinates: {latitude}, {longitude}'.format(**coord)
'Coordinates: 37.24N, -115.81W'

Accessing arguments' attributes:

>>> c = 3-5j
>>> ('The complex number {0} is formed from the real part {0.real} '
... 'and the imaginary part {0.imag}.').format(c)
'The complex number (3-5j) is formed from the real part 3.0 and the imaginary part -5.0.'
>>> class Point:
... def __init__(self, x, y):
... self.x, self.y = x, y
... def __str__(self):
... return 'Point({self.x}, {self.y})'.format(self=self)
...
>>> str(Point(4, 2))
'Point(4, 2)'

Accessing arguments' items:

>>> coord = (3, 5)
>>> 'X: {0[0]}; Y: {0[1]}'.format(coord)
'X: 3; Y: 5'

Replacing %s and %r:

>>> "repr() shows quotes: {!r}; str() doesn't: {!s}".format('test1', 'test2')
"repr() shows quotes: 'test1'; str() doesn't: test2"

Aligning the text and specifying a width:

>>> '{:<30}'.format('left aligned')
'left aligned '
>>> '{:>30}'.format('right aligned')
' right aligned'
>>> '{:^30}'.format('centered')
' centered '
>>> '{:*^30}'.format('centered') # use '*' as a fill char
'***********centered***********'

Replacing %+f, %-f, and % f and specifying a sign:

>>> '{:+f}; {:+f}'.format(3.14, -3.14)  # show it always
'+3.140000; -3.140000'
>>> '{: f}; {: f}'.format(3.14, -3.14) # show a space for positive numbers
' 3.140000; -3.140000'
>>> '{:-f}; {:-f}'.format(3.14, -3.14) # show only the minus -- same as '{:f}; {:f}'
'3.140000; -3.140000'

Replacing %x and %o and converting the value to different bases:

>>> # format also supports binary numbers
>>> "int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}".format(42)
'int: 42; hex: 2a; oct: 52; bin: 101010'
>>> # with 0x, 0o, or 0b as prefix:
>>> "int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}".format(42)
'int: 42; hex: 0x2a; oct: 0o52; bin: 0b101010'

Using the comma as a thousands separator:

>>> '{:,}'.format(1234567890)
'1,234,567,890'

Expressing a percentage:

>>> points = 19
>>> total = 22
>>> 'Correct answers: {:.2%}'.format(points/total)
'Correct answers: 86.36%'

Using type-specific formatting:

>>> import datetime
>>> d = datetime.datetime(2010, 7, 4, 12, 15, 58)
>>> '{:%Y-%m-%d %H:%M:%S}'.format(d)
'2010-07-04 12:15:58'

Nesting arguments and more complex examples:

>>> for align, text in zip('<^>', ['left', 'center', 'right']):
... '{0:{fill}{align}16}'.format(text, fill=align, align=align)
...
'left<<<<<<<<<<<<'
'^^^^^center^^^^^'
'>>>>>>>>>>>right'
>>>
>>> octets = [192, 168, 0, 1]
>>> '{:02X}{:02X}{:02X}{:02X}'.format(*octets)
'C0A80001'
>>> int(_, 16)
3232235521
>>>
>>> width = 5
>>> for num in range(5,12):
... for base in 'dXob':
... print('{0:{width}{base}}'.format(num, base=base, width=width), end=' ')
... print()
...
5 5 5 101
6 6 6 110
7 7 7 111
8 8 10 1000
9 9 11 1001
10 A 12 1010
11 B 13 1011

Ex 1: Basic use of format with positional arguments

Illustrated usage of format with basic positional arguments:

Here, Argument 0 is the string "Adam" and Argument 1 is the floating number 230.2346. (Note that the argument list for format starts at 0.)

The string "Hello {0}, your balance is {1:9.3f}" is the template string. This contains the format codes for formatting. The curly braces are just placeholders for the arguments to be placed. In the above example, {0} is placeholder for "Adam" and {1:9.3f} is placeholder for 230.2346. Since the template string references format() arguments as {0} and {1}, the arguments are positional arguments. They both can also be referenced without the numbers as {} and Python internally converts them to numbers.

Internally, we have the following:

  • Since "Adam" is the 0th argument, it is substituted in place of {0}. Since, {0} doesn't contain any other format codes, it doesn't perform any other operations.
  • However, this is not the case for the 1st argument of 230.2346. Here, {1:9.3f} places 230.2346 in its place and performs the operation 9.3f.
  • As noted in the format specifier table above, f specifies the format is dealing with a float number. If not correctly specified, an error will be raised.
  • The numeral before "." (i.e., 9 in this case) specifies the minimum width/padding the number (230.2346) can take. In this case, 230.2346 is allotted a minimum of 9 places including the ".". If no alignment option is specified, the number is aligned to the right of the remaining spaces. (For strings, the string is aligned to the left.)
  • The numeral after "." (i.e., 3 in this case) truncates the decimal part (i.e., 2346 in this case) up to the given number. Here, 2346 is truncated after 3 places. The remaining numeric portion, if it exists, is rounded (hence, the remaining portion of 46 here is rounded to 50 resulting in 2346 being truncated to 235).

Ex 2: Basic use of format with keyword arguments

We've used the same example from before to show the difference between keyword and positional arguments. Here, instead of just the parameters, we've used key-value pairings for the parameters. Namely, name="Adam" and blc=230.2346. Since these parameters are referenced by their keys as {name} and {blc:9.3f}, they are known as keyword or named arguments.

Internally,

  • The placeholder {name} is replaced by the value of name - "Adam". Since it doesn't contain any other format codes, "Adam" is placed.
  • For the argument blc=230.2346, the placeholder {blc:9.3f} is replaced by the value 230.2346. But before replacing it, like previous example, it performs 9.3f operation on it. This outputs 230.235. The decimal part is truncated after 3 places and remaining digits are rounded off. Likewise, the total width is assigned 9 leaving two spaces to the left.

Ex 3: Basic formatting for default, positional and keyword arguments
# default arguments
print("Hello {}, your balance is {}.".format("Adam", 230.2346))

# positional arguments
print("Hello {0}, your balance is {1}.".format("Adam", 230.2346))

# keyword arguments
print("Hello {name}, your balance is {blc}.".format(name="Adam", blc=230.2346))

# mixed arguments
print("Hello {0}, your balance is {blc}.".format("Adam", blc=230.2346))

Output:

Hello Adam, your balance is 230.2346.
Hello Adam, your balance is 230.2346.
Hello Adam, your balance is 230.2346.
Hello Adam, your balance is 230.2346.

Note that when arguments are mixed (i.e., positional as well as keyword arguments are provided) the keyword arguments must always follow the positional arguments.


Ex 4: Simple number formatter (integer, float, octal, binary, and hexadecimal)
# integer arguments
print("The number is: {:d}".format(123))

# float arguments
print("The float number is: {:f}".format(123.4567898))

# octal, binary and hexadecimal format
print("bin: {0:b}, oct: {0:o}, hex: {0:x}".format(12))

Output:

The number is: 123
The float number is: 123.456790
bin: 1100, oct: 14, hex: c

Ex 5: Number formatting with padding for ints and floats
# integer numbers with minimum width
print("{:5d}".format(12))

# width doesn't work for numbers longer than padding
print("{:2d}".format(1234))

# padding for float numbers
print("{:8.3f}".format(12.2346))

# integer numbers with minimum width filled with zeros
print("{:05d}".format(12))

# padding for float numbers filled with zeros
print("{:08.3f}".format(12.2346))

Output:

   12
1234
12.235
00012
0012.235

Notes:

  • In the first statement, {:5d} takes an integer argument and assigns a minimum width of 5. Since, no alignment is specified, the number is aligned to the right (recall that numbers are aligned to the right by default while strings are aligned to the left by default).
  • In the second statement, we can see the minimum width (i.e., 2) is less than the width of the provided number (i.e., 1234), so space is not impacted and the number is not truncated.
  • Unlike integers, floats have both integer and decimal parts. The mininum width, if provided, applies to both integer and decimal parts as a whole including .. Hence, once 12.2346 is rounded to three decimal places for precision, we get 12.235, which has a width of 6. Since the minimum specified is 8, we end up with the following (note the two empty spaces at the beginning and the default right alignment): 12.235
  • If specifying a minimum width leaves unoccupied space, then you can optionally fill that space with zeroes by placing a zero before the format specifier. This will work for both integers and floats: {:05d} and {:08.3f}.

Ex 6: Number formatting for signed numbers
# show the + sign
print("{:+f} {:+f}".format(12.23, -12.23))

# show the - sign only
print("{:-f} {:-f}".format(12.23, -12.23))

# show space for + sign
print("{: f} {: f}".format(12.23, -12.23))

Output:

+12.230000 -12.230000
12.230000 -12.230000
12.230000 -12.230000

Ex 7: Number formatting with left, right, and center alignment
# integer numbers with right alignment (default)
print("{:5d}".format(12))

# float numbers with center alignment
print("{:^10.3f}".format(12.2346))

# integer left alignment filled with zeros
print("{:<05d}".format(12))

# float numbers with center alignment
print("{:=8.3f}".format(-12.2346))

Output:

   12
12.235
12000
- 12.235

Note: Left alignment filled with zeros for integer numbers can cause problems as the 3rd example which returns 12000, rather than 12.


Ex 8: String formatting with padding and alignment
# string padding with left alignment
print("{:5}".format("cat"))

# string padding with right alignment
print("{:>5}".format("cat"))

# string padding with center alignment
print("{:^5}".format("cat"))

# string padding with center alignment
# and '*' padding character
print("{:*^5}".format("cat"))

Output:

cat  
cat
cat
*cat*

Ex 9: Truncating strings
# truncating strings to 3 letters
print("{:.3}".format("caterpillar"))

# truncating strings to 3 letters
# and padding
print("{:5.3}".format("caterpillar"))

# truncating strings to 3 letters,
# padding and center alignment
print("{:^5.3}".format("caterpillar"))

Output:

cat
cat
cat

Ex 10: Formatting class members
# define Person class
class Person:
age = 23
name = "Adam"

# format age
print("{p.name}'s age is: {p.age}".format(p=Person()))

Output:

Adam's age is: 23

Here, the Person object is passed as a keyword argument p. Inside the template string, Person's name and age attributes are accessed using .name and .age respectively.


Ex 11: Formatting dictionary members
# define Person dictionary
person = {'age': 23, 'name': 'Adam'}

# format age
print("{p[name]}'s age is: {p[age]}".format(p=person))

Output:

Adam's age is: 23

The person dictionary is passed as a keyword argument p, and the behavior exhibited here is similar to that exhibited by classes. Inside the template string, person's name and age values are accessed using [name] and [age] respectively.


Ex 12: Arguments as format codes

You can pass format codes like precision, alignment, fill character as positional or keyword arguments dynamically:

# dynamic string format template
string = "{:{fill}{align}{width}}"

# passing format codes as arguments
print(string.format('cat', fill='*', align='^', width=5))

# dynamic float format template
num = "{:{align}{width}.{precision}f}"

# passing format codes as arguments
print(num.format(123.236, align='<', width=8, precision=2))

Output:

*cat*
123.24

Notes:

  • In the first example, 'cat' is the positional argument is to be formatted. Likewise, fill='*', align='^', and width=5 are keyword arguments.
  • In the template string, these keyword arguments are not retrieved as normal strings to be printed but as the actual format codes fill, align, and width. The arguments replace the corresponding named placeholders and the string 'cat' is formatted accordingly.
  • Likewise, in the second example, 123.236 is the positional argument and, align, width and precision are passed to the template string as format codes.

Ex 13: Type-specific formatting (datetime and complex numbers)

format() also supports type-specific formatting options like datetime (see here for more about formatting codes for datetime) and complex number formatting. format() internally calls __format__() for datetime, while format() accesses the attributes of the complex number. You can easily override the __format__() method of any object for custom formatting.

import datetime
# datetime formatting
date = datetime.datetime.now()
print("It's now: {:%Y/%m/%d %H:%M:%S}".format(date))

# complex number formatting
complexNumber = 1+2j
print("Real part: {0.real} and Imaginary part: {0.imag}".format(complexNumber))

# custom __format__() method
class Person:
def __format__(self, format):
if(format == 'age'):
return '23'
return 'None'

print("Adam's age is: {:age}".format(Person()))

Output:

It's now: 2021/05/31 18:13:06
Real part: 1.0 and Imaginary part: 2.0
Adam's age is: 23

Notes:

  • For datetime: Current datetime is passed as a positional argument to the format() method. And, internally using __format__() method, format() accesses the year, month, day, hour, minutes and seconds. (See this post for how to remove undesired leading zeroes; TLDR: use a dash after % like %Y/%-m/%-d to remove leading zeroes for the month and day.)
  • For complex numbers: 1+2j is internally converted to a ComplexNumber object. Then accessing its attributes real and imag, the number is formatted.
  • Overriding __format__(): Like datetime, you can override your own __format__() method for custom formatting which returns age when accessed as {:age}


format_map(mapping)

Description: tbd

Examples:

Ex 0: Documentation

Similar to str.format(**mapping), except that mapping is used directly and not copied to a dict. This is useful if for example mapping is a dict subclass:

>>> class Default(dict):
... def __missing__(self, key):
... return key
...
>>> '{name} was born in {country}'.format_map(Default(name='Guido'))
'Guido was born in country'

New in version 3.2.



index(sub[, start[, end]])

Description: tbd

Examples:

Ex 0: Documentation

Like find(), but raise ValueError when the substring is not found.



isalnum()

Description: tbd

Examples:

Ex 0: Documentation

Return True if all characters in the string are alphanumeric and there is at least one character, False otherwise. A character c is alphanumeric if one of the following returns True: c.isalpha(), c.isdecimal(), c.isdigit(), or c.isnumeric().



isalpha()

Description: tbd

Examples:

Ex 0: Documentation

Return True if all characters in the string are alphabetic and there is at least one character, False otherwise. Alphabetic characters are those characters defined in the Unicode character database as "Letter", i.e., those with general category property being one of "Lm", "Lt", "Lu", "Ll", or "Lo". Note that this is different from the "Alphabetic" property defined in the Unicode Standard.



isascii()

Description: tbd

Examples:

Ex 0: Documentation

Return True if the string is empty or all characters in the string are ASCII, False otherwise. ASCII characters have code points in the range U+0000-U+007F.

New in version 3.7.



isdecimal()

Description: tbd

Examples:

Ex 0: Documentation

Return True if all characters in the string are decimal characters and there is at least one character, False otherwise. Decimal characters are those that can be used to form numbers in base 10, e.g. U+0660, ARABIC-INDIC DIGIT ZERO. Formally a decimal character is a character in the Unicode General Category “Nd”.



isdigit()

Description: tbd

Examples:

Ex 0: Documentation

Return True if all characters in the string are digits and there is at least one character, False otherwise. Digits include decimal characters and digits that need special handling, such as the compatibility superscript digits. This covers digits which cannot be used to form numbers in base 10, like the Kharosthi numbers. Formally, a digit is a character that has the property value Numeric_Type=Digit or Numeric_Type=Decimal.



isidentifier()

Description: tbd

Examples:

Ex 0: Documentation

Return True if the string is a valid identifier according to the language definition, section Identifiers and keywords.

Call keyword.iskeyword() to test whether string s is a reserved identifier, such as def and class.

Example:

>>> from keyword import iskeyword

>>> 'hello'.isidentifier(), iskeyword('hello')
True, False
>>> 'def'.isidentifier(), iskeyword('def')
True, True


islower()

Description: tbd

Examples:

Ex 0: Documentation

Return True if all cased characters in the string are lowercase and there is at least one cased character, False otherwise.



isnumeric()

Description: tbd

Examples:

Ex 0: Documentation

Return True if all characters in the string are numeric characters, and there is at least one character, False otherwise. Numeric characters include digit characters, and all characters that have the Unicode numeric value property, e.g. U+2155, VULGAR FRACTION ONE FIFTH. Formally, numeric characters are those with the property value Numeric_Type=Digit, Numeric_Type=Decimal or Numeric_Type=Numeric.



isprintable()

Description: tbd

Examples:

Ex 0: Documentation

Return True if all characters in the string are printable or the string is empty, False otherwise. Nonprintable characters are those characters defined in the Unicode character database as “Other” or “Separator”, excepting the ASCII space (0x20) which is considered printable. (Note that printable characters in this context are those which should not be escaped when repr() is invoked on a string. It has no bearing on the handling of strings written to sys.stdout or sys.stderr.)



isspace()

Description: tbd

Examples:

Ex 0: Documentation

Return True if there are only whitespace characters in the string and there is at least one character, False otherwise.

A character is whitespace if in the Unicode character database (see unicodedata), either its general category is Zs (“Separator, space”), or its bidirectional class is one of WS, B, or S.



istitle()

Description: tbd

Examples:

Ex 0: Documentation

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.



isupper()

Description: tbd

Examples:

Ex 0: Documentation

Return True if all cased characters in the string are uppercase and there is at least one cased character, False otherwise.

>>> 'BANANA'.isupper()
True
>>> 'banana'.isupper()
False
>>> 'baNana'.isupper()
False
>>> ' '.isupper()
False


join(iterable)

Description: tbd

Examples:

Ex 0: Documentation

Return a string which is the concatenation of the strings in iterable. A TypeError will be raised if there are any non-string values in iterable, including bytes objects. The separator between elements is the string providing this method.



ljust(width[, fillchar])

Description: tbd

Examples:

Ex 0: Documentation

Return the string left justified in a string of length width. Padding is done using the specified fillchar (default is an ASCII space). The original string is returned if width is less than or equal to len(s).



lower()

Description: tbd

Examples:

Ex 0: Documentation

Return a copy of the string with all the cased characters converted to lowercase.

The lowercasing algorithm used is described in section 3.13 of the Unicode Standard.



lstrip([chars])

Description: tbd

Examples:

Ex 0: Documentation

Return a copy of the string with leading characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a prefix; rather, all combinations of its values are stripped:

>>> '   spacious   '.lstrip()
'spacious '
>>> 'www.example.com'.lstrip('cmowz.')
'example.com'

See str.removeprefix() for a method that will remove a single prefix string rather than all of a set of characters. For example:

>>> 'Arthur: three!'.lstrip('Arthur: ')
'ee!'
>>> 'Arthur: three!'.removeprefix('Arthur: ')
'three!'


maketrans(x[, y[, z]])

Description: tbd

Examples:

Ex 0: Documentation

This static method returns a translation table usable for str.translate().

If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters (strings of length 1) to Unicode ordinals, strings (of arbitrary lengths) or None. Character keys will then be converted to ordinals.

If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the character at the same position in y. If there is a third argument, it must be a string, whose characters will be mapped to None in the result.



partition(sep)

Description: tbd

Examples:

Ex 0: Documentation

Split the string at the first occurrence of sep, 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.



removeprefix(prefix, /)

Description: tbd

Examples:

Ex 0: Documentation

If the string starts with the prefix string, return string[len(prefix):]. Otherwise, return a copy of the original string:

>>> 'TestHook'.removeprefix('Test')
'Hook'
>>> 'BaseTestCase'.removeprefix('Test')
'BaseTestCase'

New in version 3.9.



removesuffix(suffix, /)

Description: tbd

Examples:

Ex 0: Documentation

If the string ends with the suffix string and that suffix is not empty, return string[:-len(suffix)]. Otherwise, return a copy of the original string:

>>> 'MiscTests'.removesuffix('Tests')
'Misc'
>>> 'TmpDirMixin'.removesuffix('Tests')
'TmpDirMixin'

New in version 3.9.



replace(old, new[, count])

Description: tbd

Examples:

Ex 0: Documentation

Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.



rfind(sub[, start[, end]])

Description: tbd

Examples:

Ex 0: Documentation

Return the highest index in the string where substring sub is found, such that sub is contained within s[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 on failure.



rindex(sub[, start[, end]])

Description: Recall how rfind(sub[, start[, end]]) works:

Return the highest index in the string where substring sub is found, such that sub is contained within s[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 on failure.

Examples:

Ex 0: Documentation

Like rfind() but raises ValueError when the substring sub is not found.


Ex 1: Finding the length of a string without using len

A good example of use for rindex is finding the length of a string without using len (see this Stack Overflow answer for reference):

def strlen(s):
if s == "": return 0
return s.rindex(s[-1]) + 1

In other words, it doesn't work by counting the characters, so it should be just as fast for a 1GB string as it is for a 1 byte string.

It works by looking at the last character and searching from the very end to find that character. Since it's the last character it will always find it at the first place it looks, essentially always returning the index of the last character. The length is just one more than the index of the last character.



rjust(width[, fillchar])

Description: tbd

Examples:

Ex 0: Documentation

Return the string right justified in a string of length width. Padding is done using the specified fillchar (default is an ASCII space). The original string is returned if width is less than or equal to len(s).



rpartition(sep)

Description: tbd

Examples:

Ex 0: Documentation

Split the string at the last occurrence of sep, 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.



rsplit(sep=None, maxsplit=-1)

Description: tbd

Examples:

Ex 0: Documentation

Return a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done, the rightmost ones. If sep is not specified or None, any whitespace string is a separator. Except for splitting from the right, rsplit() behaves like split() which is described in detail below.



rstrip([chars])

Description: tbd

Examples:

Ex 0: Documentation

Return a copy of the string with trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a suffix; rather, all combinations of its values are stripped:

>>> '   spacious   '.rstrip()
' spacious'
>>> 'mississippi'.rstrip('ipz')
'mississ'

See str.removesuffix() for a method that will remove a single suffix string rather than all of a set of characters. For example:

>>> 'Monty Python'.rstrip(' Python')
'M'
>>> 'Monty Python'.removesuffix(' Python')
'Monty'


split(sep=None, maxsplit=-1)

Description: tbd

Examples:

Ex 0: Documentation

Return a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done (thus, the list will have at most maxsplit+1 elements). If maxsplit is not specified or -1, then there is no limit on the number of splits (all possible splits are made).

If sep is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings (for example, '1,,2'.split(',') returns ['1', '', '2']). The sep argument may consist of multiple characters (for example, '1<>2<>3'.split('<>') returns ['1', '2', '3']). Splitting an empty string with a specified separator returns [''].

For example:

>>> '1,2,3'.split(',')
['1', '2', '3']
>>> '1,2,3'.split(',', maxsplit=1)
['1', '2,3']
>>> '1,2,,3,'.split(',')
['1', '2', '', '3', '']

If sep is not specified or is None, 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 None separator returns [].

For example:

>>> '1 2 3'.split()
['1', '2', '3']
>>> '1 2 3'.split(maxsplit=1)
['1', '2 3']
>>> ' 1 2 3 '.split()
['1', '2', '3']


splitlines([keepends])

Description: tbd

Examples:

Ex 0: Documentation

Return a list of the lines in the string, breaking at line boundaries. Line breaks are not included in the resulting list unless keepends is given and true.

This method splits on the following line boundaries. In particular, the boundaries are a superset of universal newlines.

RepresentationDescription
\nLine Feed
\rCarriage Return
\r\nCarriage Return + Line Feed
\v or \x0bLine Tabulation
\f or \x0cForm Feed
\x1cFile Separator
\x1dGroup Separator
\x1eRecord Separator
\x85Next Line (C1 Control Code)
\u2028Line Separator
\u2029Paragraph Separator

Changed in version 3.2: \v and \f added to list of line boundaries.

For example:

>>> 'ab c\n\nde fg\rkl\r\n'.splitlines()
['ab c', '', 'de fg', 'kl']
>>> 'ab c\n\nde fg\rkl\r\n'.splitlines(keepends=True)
['ab c\n', '\n', 'de fg\r', 'kl\r\n']

Unlike split() when a delimiter string sep is given, this method returns an empty list for the empty string, and a terminal line break does not result in an extra line:

>>> "".splitlines()
[]
>>> "One line\n".splitlines()
['One line']

For comparison, split('\n') gives:

>>> ''.split('\n')
['']
>>> 'Two lines\n'.split('\n')
['Two lines', '']


startswith(prefix[, start[, end]])

Description: tbd

Examples:

Ex 0: Documentation

Return True if string starts with the prefix, otherwise return False. prefix can also be a tuple of prefixes to look for. With optional start, test string beginning at that position. With optional end, stop comparing string at that position.



strip([chars])

Description: tbd

Examples:

Ex 0: Documentation

Return a copy of the string with the leading and trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped:

>>> '   spacious   '.strip()
'spacious'
>>> 'www.example.com'.strip('cmowz.')
'example'

The outermost leading and trailing chars argument values are stripped from the string. Characters are removed from the leading end until reaching a string character that is not contained in the set of characters in chars. A similar action takes place on the trailing end. For example:

>>> comment_string = '#....... Section 3.2.1 Issue #32 .......'
>>> comment_string.strip('.#! ')
'Section 3.2.1 Issue #32'


swapcase()

Description: tbd

Examples:

Ex 0: Documentation

Return a copy of the string with uppercase characters converted to lowercase and vice versa. Note that it is not necessarily true that s.swapcase().swapcase() == s.



title()

Description: tbd

Examples:

Ex 0: Documentation

Return a titlecased version of the string where words start with an uppercase character and the remaining characters are lowercase.

For example:

>>> 'Hello world'.title()
'Hello World'

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:

>>> "they're bill's friends from the UK".title()
"They'Re Bill'S Friends From The Uk"

A workaround for apostrophes can be constructed using regular expressions:

>>> import re
>>> def titlecase(s):
... return re.sub(r"[A-Za-z]+('[A-Za-z]+)?",
... lambda mo: mo.group(0).capitalize(),
... s)
...
>>> titlecase("they're bill's friends.")
"They're Bill's Friends."


translate(table)

Description: tbd

Examples:

Ex 0: Documentation

Return a copy of the string in which each character has been mapped through the given translation table. The table must be an object that implements indexing via __getitem__(), typically a mapping or sequence. When indexed by a Unicode ordinal (an integer), the table object can do any of the following: return a Unicode ordinal or a string, to map the character to one or more other characters; return None, to delete the character from the return string; or raise a LookupError exception, to map the character to itself.

You can use str.maketrans() to create a translation map from character-to-character mappings in different formats.

See also the codecs module for a more flexible approach to custom character mappings.



upper()

Description: tbd

Examples:

Ex 0: Documentation

Return a copy of the string with all the cased characters converted to uppercase. Note that s.upper().isupper() might be False if s contains uncased characters or if the Unicode category of the resulting character(s) is not “Lu” (Letter, uppercase), but e.g. “Lt” (Letter, titlecase).

The uppercasing algorithm used is described in section 3.13 of the Unicode Standard.



zfill(width)

Description: tbd

Examples:

Ex 0: Documentation

Return a copy of the string left filled with ASCII '0' digits to make a string of length width. A leading sign prefix ('+'/'-') is handled by inserting the padding after the sign character rather than before. The original string is returned if width is less than or equal to len(s).

For example:

>>> "42".zfill(5)
'00042'
>>> "-42".zfill(5)
'-0042'


List Methods

Examples from the docs
>>> fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']

>>> fruits.count('apple')
2

>>> fruits.count('tangerine')
0

>>> fruits.index('banana')
3

>>> fruits.index('banana', 4) # Find next banana starting a position 4
6

>>> fruits.reverse()

>>> fruits
['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange']

>>> fruits.append('grape')

>>> fruits
['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange', 'grape']

>>> fruits.sort()

>>> fruits
['apple', 'apple', 'banana', 'banana', 'grape', 'kiwi', 'orange', 'pear']

>>> fruits.pop()
'pear'

You might have noticed that methods like insert, remove or sort that only modify the list have no return value printed – they return the default None. This is a design principle for all mutable data structures in Python.

Another thing you might notice is that not all data can be sorted or compared. For instance, [None, 'hello', 10] doesn't sort because integers can't be compared to strings and None can't be compared to other types. Also, there are some types that don't have a defined ordering relation. For example, 3+4j < 5+7j isn't a valid comparison.


append(x)

Description: The append() method adds an item to the end of the list:

currencies = ['Dollar', 'Euro', 'Pound']

# append 'Yen' to the list
currencies.append('Yen')

print(currencies)

# Output: ['Dollar', 'Euro', 'Pound', 'Yen']

The syntax of the append() method is: list.append(item)

The method takes a single argument:

  • item - an item (number, string, list etc.) to be added at the end of the list

The method doesn't return any value (i.e., returns None).

Examples:

Ex 0: Documentation

Add an item to the end of the list. Equivalent to a[len(a):] = [x].


Ex 1: Adding element to a list
# animals list
animals = ['cat', 'dog', 'rabbit']

# Add 'guinea pig' to the list
animals.append('guinea pig')

print('Updated animals list: ', animals)

Output:

Updated animals list:  ['cat', 'dog', 'rabbit', 'guinea pig']

Ex 2: Adding list to a list
# animals list
animals = ['cat', 'dog', 'rabbit']

# list of wild animals
wild_animals = ['tiger', 'fox']

# appending wild_animals list to animals
animals.append(wild_animals)

print('Updated animals list: ', animals)

Output:

Updated animals list:  ['cat', 'dog', 'rabbit', ['tiger', 'fox']]

In the program, a single item (wild_animals list) is added to the animals list.

Note: If you need to add items of a list (rather than the list itself) to another list, use the extend() method.



clear()

Description: The clear() method removes all items from the list.

prime_numbers = [2, 3, 5, 7, 9, 11]

# remove all elements
prime_numbers.clear()

# Updated prime_numbers List
print('List after clear():', prime_numbers)


# Output: List after clear(): []
  • The syntax of clear() method is: list.clear()
  • The clear() method doesn't take any parameters.
  • The clear() method only empties the given list. It doesn't return any value.

Examples:

Ex 0: Documentation

Remove all items from the list. Equivalent to del a[:].


Ex 1: Working of clear() method
# Defining a list
list = [{1, 2}, ('a'), ['1.1', '2.2']]

# clearing the list
list.clear()


print('List:', list)

Output:

List: []

Note: If you are using Python 2 or Python 3.2 and below, you cannot use the clear() method. You can use the del operator instead.


Ex 2: Emptying the list using del
# Defining a list
list = [{1, 2}, ('a'), ['1.1', '2.2']]

# clearing the list
del list[:]


print('List:', list)

Output:

List: []


copy()

Description: The copy() method returns a shallow copy of the list.

# mixed list
prime_numbers = [2, 3, 5]

# copying a list
numbers = prime_numbers.copy()


print('Copied List:', numbers)

# Output: Copied List: [2, 3, 5]
  • The syntax of the copy() method is: new_list = list.copy()
  • The copy() method doesn't take any parameters.
  • The copy() method returns a new list. It doesn't modify the original list.

Examples:

Ex 0: Documentation

Return a shallow copy of the list. Equivalent to a[:].


Ex 1: Copying a list
# mixed list
my_list = ['cat', 0, 6.7]

# copying a list
new_list = my_list.copy()


print('Copied List:', new_list)

Output:

Copied List: ['cat', 0, 6.7]

If you modify the new_list in the above example, my_list will not be modified.


Ex 2: List copy using =

We can also use the = operator to copy a list. For example,

old_list = [1, 2, 3]
new_list = old_list

However, there is one problem with copying lists in this way. If you modify new_list, old_list is also modified. It is because the new list is referencing or pointing to the same old_list object.

old_list = [1, 2, 3]

# copy list using =
new_list = old_list


# add an element to list
new_list.append('a')

print('New List:', new_list)
print('Old List:', old_list)

Output:

Old List: [1, 2, 3, 'a']
New List: [1, 2, 3, 'a']

However, if you need the original list unchanged when the new list is modified, you can use the copy() method.


Ex 3: Copy list using slicing syntax
# shallow copy using the slicing syntax

# mixed list
list = ['cat', 0, 6.7]

# copying a list using slicing
new_list = list[:]


# Adding an element to the new list
new_list.append('dog')

# Printing new and old list
print('Old List:', list)
print('New List:', new_list)

Output:

Old List: ['cat', 0, 6.7]
New List: ['cat', 0, 6.7, 'dog']


count(x)

Description: The count() method returns the number of times the specified element appears in the list.

# create a list
numbers = [2, 3, 5, 2, 11, 2, 7]

# check the count of 2
count = numbers.count(2)


print('Count of 2:', count)

# Output: Count of 2: 3
  • The syntax of the count() method is: list.count(element)
  • The count() method takes a single argument:
    • element - the element to be counted
  • The count() method returns the number of times element appears in the list.

Examples:

Ex 0: Documentation

Return the number of times x appears in the list.


Ex 1: Use of count()
# vowels list
vowels = ['a', 'e', 'i', 'o', 'i', 'u']

# count element 'i'
count = vowels.count('i')


# print count
print('The count of i is:', count)

# count element 'p'
count = vowels.count('p')


# print count
print('The count of p is:', count)

Output:

The count of i is: 2
The count of p is: 0

Ex 2: Count tuple and list elements inside list
# random list
random = ['a', ('a', 'b'), ('a', 'b'), [3, 4]]

# count element ('a', 'b')
count = random.count(('a', 'b'))

# print count
print("The count of ('a', 'b') is:", count)

# count element [3, 4]
count = random.count([3, 4])

# print count
print("The count of [3, 4] is:", count)

Output:

The count of ('a', 'b') is: 2
The count of [3, 4] is: 1


extend(iterable)

Description: The extend() method adds all the elements of an iterable (list, tuple, string etc.) to the end of the list in-place.

# create a list
prime_numbers = [2, 3, 5]

# create another list
numbers = [1, 4]

# add all elements of prime_numbers to numbers
numbers.extend(prime_numbers)


print('List after extend():', numbers)

# Output: List after extend(): [1, 4, 2, 3, 5]
  • The syntax of the extend() method is: list.extend(iterable). Here, all the elements of iterable are added to the end of list.
  • The extend() method takes an iterable such as list, tuple, string, etc.
  • The extend() method modifies the original list in-place. It doesn't return any value.

Examples:

Ex 0: Documentation

Extend the list by appending all the items from the iterable. Equivalent to a[len(a):] = iterable.


Ex 1: Using extend() method
# languages list
languages = ['French', 'English']

# another list of language
languages1 = ['Spanish', 'Portuguese']

# appending language1 elements to language
languages.extend(languages1)


print('Languages List:', languages)

Output:

Languages List: ['French', 'English', 'Spanish', 'Portuguese']

Ex 2: Add elements of tuple and set to list
# languages list
languages = ['French']

# languages tuple
languages_tuple = ('Spanish', 'Portuguese')

# languages set
languages_set = {'Chinese', 'Japanese'}

# appending language_tuple elements to language
languages.extend(languages_tuple)


print('New Language List:', languages)

# appending language_set elements to language
languages.extend(languages_set)


print('Newer Languages List:', languages)

Output:

New Languages List: ['French', 'Spanish', 'Portuguese']
Newer Languages List: ['French', 'Spanish', 'Portuguese', 'Japanese', 'Chinese']

Ex 3: Using the + operator
a = [1, 2]
b = [3, 4]

a += b # a = a + b


# Output: [1, 2, 3, 4]
print('a =', a)

Output:

a = [1, 2, 3, 4]

Ex 4: Extend by using list slicing
a = [1, 2]
b = [3, 4]

a[len(a):] = b


# Output: [1, 2, 3, 4]
print('a =', a)

Output:

a = [1, 2, 3, 4]


index(x[, start[, end]])

Description: The index() method returns the index of the specified element in the list (and raises a ValueError if not found).

animals = ['cat', 'dog', 'rabbit', 'horse']

# get the index of 'dog'
index = animals.index('dog')


print(index)

# Output: 1
  • The syntax of the list index() method is: list.index(element, start, end)
  • The list index() method can take a maximum of three arguments:
    • element - the element to be searched
    • start (optional) - start searching from this index
    • end (optional) - search the element up to this index
  • The index() method returns the index of the given element in the list.
  • If the element is not found, a ValueError exception is raised.
  • Note: The index() method only returns the first occurrence of the matching element.

Examples:

Ex 0: Documentation

Return zero-based index in the list of the first item whose value is equal to x. Raises a ValueError if there is no such item.

The optional arguments start and end are interpreted as in the slice notation and are used to limit the search to a particular subsequence of the list. The returned index is computed relative to the beginning of the full sequence rather than the start argument.


Ex 1: Find the index of the element
# vowels list
vowels = ['a', 'e', 'i', 'o', 'i', 'u']

# index of 'e' in vowels
index = vowels.index('e')

print('The index of e:', index)

# element 'i' is searched
# index of the first 'i' is returned
index = vowels.index('i')


print('The index of i:', index)

Output:

The index of e: 1
The index of i: 2

Ex 2: Index of the element not present in the list
# vowels list
vowels = ['a', 'e', 'i', 'o', 'u']

# index of 'p' in vowels
index = vowels.index('p')

print('The index of p:', index)

Output:

ValueError: 'p' is not in list

Ex 3: Working of index() with start and end parameters
# alphabets list
alphabets = ['a', 'e', 'i', 'o', 'g', 'l', 'i', 'u']

# index of 'i' in alphabets
index = alphabets.index('e') # 1

print('The index of e:', index)

# 'i' after the 4th index is searched
index = alphabets.index('i', 4) # 6

print('The index of i:', index)

# 'i' between 3rd and 5th index is searched
index = alphabets.index('i', 3, 5) # Error!

print('The index of i:', index)

Output:

The index of e: 1
The index of i: 6
Traceback (most recent call last):
File "*lt;string>", line 13, in
ValueError: 'i' is not in list


insert(i, x)

Description: The insert() method inserts an element to the list at the specified index.

# create a list of vowels
vowel = ['a', 'e', 'i', 'u']

# 'o' is inserted at index 3 (4th position)
vowel.insert(3, 'o')


print('List:', vowel)

# Output: List: ['a', 'e', 'i', 'o', 'u']
  • The syntax of the insert() method is: list.insert(i, elem). Here, elem is inserted to the list at the ith index. All the elements after elem are shifted to the right.
  • The insert() method takes two parameters:
    • index - the index where the element needs to be inserted
    • element - this is the element to be inserted in the list
  • The insert() method doesn't return anything; returns None. It only updates the current list.

Examples:

Ex 0: Documentation

Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x).


Ex 1: Inserting an element into the list
# create a list of prime numbers
prime_numbers = [2, 3, 5, 7]

# insert 11 at index 4
prime_numbers.insert(4, 11)


print('List:', prime_numbers)

Output:

List: [2, 3, 5, 7, 11]

Ex 2: Inserting a tuple (as an element) into the list
mixed_list = [{1, 2}, [5, 6, 7]]

# number tuple
number_tuple = (3, 4)

# inserting a tuple to the list
mixed_list.insert(1, number_tuple)


print('Updated List:', mixed_list)

Output:

Updated List: [{1, 2}, (3, 4), [5, 6, 7]]


pop([i])

Description: The pop() method removes the item at the given index from the list and returns the removed item.

# create a list of prime numbers
prime_numbers = [2, 3, 5, 7]

# remove the element at index 2
removed_element = prime_numbers.pop(2)

print('Removed Element:', removed_element)

# Output: Removed Element: 5
  • The syntax of the pop() method is: list.pop(index)
  • The pop() method takes a single argument (i.e., index).
  • The argument passed to the method is optional. If not passed, the default index -1 is passed as an argument (index of the last item).
  • If the index passed to the method is not in range, it throws IndexError: pop index out of range exception.
  • The pop() method returns the item present at the given index. This item is also removed from the list.

Examples:

Ex 0: Documentation

Remove the item at the given position in the list, and return it. If no index is specified, a.pop() removes and returns the last item in the list. (The square brackets around the i in the method signature denote that the parameter is optional, not that you should type square brackets at that position. You will see this notation frequently in the Python Library Reference.)


Ex 1: Pop item at the given index from the list
# programming languages list
languages = ['Python', 'Java', 'C++', 'French', 'C']

# remove and return the 4th item
return_value = languages.pop(3)

print('Return Value:', return_value)

# Updated List
print('Updated List:', languages)

Output:

Return Value: French
Updated List: ['Python', 'Java', 'C++', 'C']

Ex 2: pop() without an index, and for negative indices
# programming languages list
languages = ['Python', 'Java', 'C++', 'Ruby', 'C']

# remove and return the last item
print('When index is not passed:')
print('Return Value:', languages.pop())

print('Updated List:', languages)

# remove and return the last item
print('\nWhen -1 is passed:')
print('Return Value:', languages.pop(-1))

print('Updated List:', languages)

# remove and return the third last item
print('\nWhen -3 is passed:')
print('Return Value:', languages.pop(-3))

print('Updated List:', languages)

Output:

When index is not passed:
Return Value: C
Updated List: ['Python', 'Java', 'C++', 'Ruby']

When -1 is passed:
Return Value: Ruby
Updated List: ['Python', 'Java', 'C++']

When -3 is passed:
Return Value: Python
Updated List: ['Java', 'C++']

If you need to remove the given item from the list, you can use the remove() method.

You can use the del statement to remove an item or slices from the list.



remove(x)

Description: The remove() method removes the first matching element (which is passed as an argument) from the list (raises a ValueError if there is no such item).

# create a list
prime_numbers = [2, 3, 5, 7, 9, 11]

# remove 9 from the list
prime_numbers.remove(9)


# Updated prime_numbers List
print('Updated List: ', prime_numbers)

# Output: Updated List: [2, 3, 5, 7, 11]
  • The syntax of the remove() method is: list.remove(element)
  • The remove() method takes a single element as an argument and removes it from the list.
  • If the element doesn't exist, it throws ValueError: list.remove(x): x not in list exception.
  • The remove() doesn't return any value (returns None).

Examples:

Ex 0: Documentation

Remove the first item from the list whose value is equal to x. It raises a ValueError if there is no such item.


Ex 1: Remove element from the list
# animals list
animals = ['cat', 'dog', 'rabbit', 'guinea pig']

# 'rabbit' is removed
animals.remove('rabbit')


# Updated animals List
print('Updated animals list: ', animals)

Output:

Updated animals list:  ['cat', 'dog', 'guinea pig']

Ex 2: remove() method on a list having duplicate elements

If a list contains duplicate elements, the remove() method only removes the first matching element.

# animals list
animals = ['cat', 'dog', 'dog', 'guinea pig', 'dog']

# 'dog' is removed
animals.remove('dog')


# Updated animals list
print('Updated animals list: ', animals)

Output:

Updated animals list:  ['cat', 'dog', 'guinea pig', 'dog']

Here, only the first occurrence of element 'dog' is removed from the list.


Ex 3: Deleting element that doesn't exist
# animals list
animals = ['cat', 'dog', 'rabbit', 'guinea pig']

# Deleting 'fish' element
animals.remove('fish')


# Updated animals List
print('Updated animals list: ', animals)

Output:

Traceback (most recent call last):
File ".. .. ..", line 5, in <module>
animal.remove('fish')
ValueError: list.remove(x): x not in list

Here, we are getting an error because the animals list doesn't contain 'fish'.

If you need to delete elements based on the index (like the fourth element), you can use the pop() method.

Also, you can use the Python del statement to remove items from the list.



reverse()

Description: The reverse() method reverses the elements of the list in-place.

# create a list of prime numbers
prime_numbers = [2, 3, 5, 7]

# reverse the order of list elements
prime_numbers.reverse()


print('Reversed List:', prime_numbers)

# Output: Reversed List: [7, 5, 3, 2]
  • The syntax of the reverse() method is: list.reverse()
  • The reverse() method doesn't take any arguments.
  • The reverse() method doesn't return any value. It updates the existing list.

Examples:

Ex 0: Documentation

Reverse the elements of the list in place.


Ex 1: Reverse a list
# Operating System List
systems = ['Windows', 'macOS', 'Linux']
print('Original List:', systems)

# List Reverse
systems.reverse()


# updated list
print('Updated List:', systems)

Output:

Original List: ['Windows', 'macOS', 'Linux']
Updated List: ['Linux', 'macOS', 'Windows']

There are other several ways to reverse a list.


Ex 2: Reverse a list using slice operator
# Operating System List
systems = ['Windows', 'macOS', 'Linux']
print('Original List:', systems)

# Reversing a list
# Syntax: reversed_list = systems[start:stop:step]
reversed_list = systems[::-1]


# updated list
print('Updated List:', reversed_list)

Output:

Original List: ['Windows', 'macOS', 'Linux']
Updated List: ['Linux', 'macOS', 'Windows']

Ex 3: Accessing elements in reversed order
# Operating System List
systems = ['Windows', 'macOS', 'Linux']

# Printing Elements in Reversed Order
for o in reversed(systems):
print(o)

Output:

Linux
macOS
Windows


sort(*, key=None, reverse=False)

Description: tbd

Examples:

Ex 0: Documentation

Sort the items of the list in place (the arguments can be used for sort customization, see sorted() for their explanation).



Dictionary Methods

For several of the entries below, d refers to the dictionary d.

list(d)

Description: tbd

Examples:

Ex 0: Documentation

Return a list of all the keys used in the dictionary d.



len(d)

Description: tbd

Examples:

Ex 0: Documentation

Return the number of items in the dictionary d.



d[key]

Description: tbd

Examples:

Ex 0: Documentation

Return the item of d with key key. Raises a KeyError if key is not in the map.

If a subclass of dict defines a method __missing__() and key is not present, the d[key] operation calls that method with the key key as argument. The d[key] operation then returns or raises whatever is returned or raised by the __missing__(key) call. No other operations or methods invoke __missing__(). If __missing__() is not defined, KeyError is raised. __missing__() must be a method; it cannot be an instance variable:

>>> class Counter(dict):
... def __missing__(self, key):
... return 0
>>> c = Counter()
>>> c['red']
0
>>> c['red'] += 1
>>> c['red']
1

The example above shows part of the implementation of collections.Counter. A different __missing__ method is used by collections.defaultdict.



d[key] = value

Description: tbd

Examples:

Ex 0: Documentation

Set d[key] to value.



del d[key]

Description: tbd

Examples:

Ex 0: Documentation

Remove d[key] from d. Raises a KeyError if key is not in the map.



key in d

Description: tbd

Examples:

Ex 0: Documentation

Return True if d has a key key, else False.



key not in d

Description: tbd

Examples:

Ex 0: Documentation

Equivalent to not key in d.



iter(d)

Description: tbd

Examples:

Ex 0: Documentation

Return an iterator over the keys of the dictionary. This is a shortcut for iter(d.keys()).



clear()

Description: tbd

Examples:

Ex 0: Documentation

Remove all items from the dictionary.



copy()

Description: tbd

Examples:

Ex 0: Documentation

Return a shallow copy of the dictionary.



fromkeys(iterable[, value])

Description: tbd

Examples:

Ex 0: Documentation

Create a new dictionary with keys from iterable and values set to value.

fromkeys() is a class method that returns a new dictionary. value defaults to None. All of the values refer to just a single instance, so it generally doesn’t make sense for value to be a mutable object such as an empty list. To get distinct values, use a dict comprehension instead.



get(key[, default])

Description: tbd

Examples:

Ex 0: Documentation

Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError.



items()

Description: tbd

Examples:

Ex 0: Documentation

Return a new view of the dictionary’s items ((key, value) pairs). See the documentation of view objects.



keys()

Description: tbd

Examples:

Ex 0: Documentation

Return a new view of the dictionary’s keys. See the documentation of view objects.



pop(key[, default])

Description: tbd

Examples:

Ex 0: Documentation

If key is in the dictionary, remove it and return its value, else return default. If default is not given and key is not in the dictionary, a KeyError is raised.



popitem()

Description: tbd

Examples:

Ex 0: Documentation

Remove and return a (key, value) pair from the dictionary. Pairs are returned in LIFO order.

popitem() is useful to destructively iterate over a dictionary, as often used in set algorithms. If the dictionary is empty, calling popitem() raises a KeyError.

Changed in version 3.7: LIFO order is now guaranteed. In prior versions, popitem() would return an arbitrary key/value pair.



reversed(d)

Description: tbd

Examples:

Ex 0: Documentation

Return a reverse iterator over the keys of the dictionary. This is a shortcut for reversed(d.keys()).

New in version 3.8.



setdefault(key[, default])

Description: tbd

Examples:

Ex 0: Documentation

If key is in the dictionary, return its value. If not, insert key with a value of default and return default. default defaults to None.



update([other])

Description: tbd

Examples:

Ex 0: Documentation

Update the dictionary with the key/value pairs from other, overwriting existing keys. Return None.

update() 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: d.update(red=1, blue=2).



values()

Description: tbd

Examples:

Ex 0: Documentation

Return a new view of the dictionary’s values. See the documentation of view objects.

An equality comparison between one dict.values() view and another will always return False. This also applies when comparing dict.values() to itself:

>>> d = {'a': 1}
>>> d.values() == d.values()
False


d | other

Description: tbd

Examples:

Ex 0: Documentation

Create a new dictionary with the merged keys and values of d and other, which must both be dictionaries. The values of other take priority when d and other share keys.

New in version 3.9.



d |= other

Description: tbd

Examples:

Ex 0: Documentation

Update the dictionary d with keys and values from other, which may be either a mapping or an iterable of key/value pairs. The values of other take priority when d and other share keys.

New in version 3.9.



Dictionary view objects: The objects returned by dict.keys(), dict.values() and dict.items() are view objects. They provide a dynamic view on the dictionary's entries, which means that when the dictionary changes, the view reflects these changes. Dictionary views can be iterated over to yield their respective data, and support membership tests:

len(dictview)

Description: tbd

Examples:

Ex 0: Documentation

Return the number of entries in the dictionary.



iter(dictview)

Description: tbd

Examples:

Ex 0: Documentation

Return an iterator over the keys, values or items (represented as tuples of (key, value)) in the dictionary.

Keys and values are iterated over in insertion order. This allows the creation of (value, key) pairs using zip(): pairs = zip(d.values(), d.keys()). Another way to create the same list is pairs = [(v, k) for (k, v) in d.items()].

Iterating views while adding or deleting entries in the dictionary may raise a RuntimeError or fail to iterate over all entries.

Changed in version 3.7: Dictionary order is guaranteed to be insertion order.



x in dictview

Description: tbd

Examples:

Ex 0: Documentation

Return True if x is in the underlying dictionary’s keys, values or items (in the latter case, x should be a (key, value) tuple).



reversed(dictview)

Description: tbd

Examples:

Ex 0: Documentation

Return a reverse iterator over the keys, values or items of the dictionary. The view will be iterated in reverse order of the insertion.

Changed in version 3.8: Dictionary views are now reversible.



Tuple Methods

See the "Common Sequence Operations" note at the top of this document.

Set Methods

Instances of set and frozenset provide the following operations:

len(s)

Description: tbd

Ex 0: Documentation

Return the number of elements in set s (cardinality of s).



x in s

Description: tbd

Ex 0: Documentation

Test x for membership in s.



x not in s

Description: tbd

Examples:

Ex 0: Documentation

Test x for non-membership in s.



isdisjoint(other)

Description: tbd

Examples:

Ex 0: Documentation

Return True if the set has no elements in common with other. Sets are disjoint if and only if their intersection is the empty set.



issubset(other) (alternative form: set <= other)

Description: tbd

Examples:

Ex 0: Documentation

Test whether every element in the set is in other.



set < other

Description: tbd

Examples:

Ex 0: Documentation

Test whether the set is a proper subset of other, that is, set <= other and set != other.



issuperset(other) (alternative form: set >= other)

Description: tbd

Examples:

Ex 0: Documentation

Test whether every element in other is in the set.



set > other

Description: tbd

Examples:

Ex 0: Documentation

Test whether the set is a proper superset of other, that is, set >= other and set != other.



union(*others) (alternative form: set | other | ...)

Description: tbd

Examples:

Ex 0: Documentation

Return a new set with elements from the set and all others.



intersection(*others) (alternative form: set & other & ...)

Description: tbd

Examples:

Ex 0: Documentation

Return a new set with elements common to the set and all others.



difference(*others) (alternative form: set - other - ...)

Description: tbd

Examples:

Ex 0: Documentation

Return a new set with elements in the set that are not in the others.



symmetric_difference(other) (alternative form: set ^ other)

Description: tbd

Examples:

Ex 0: Documentation

Return a new set with elements in either the set or other but not both.



copy()

Description: tbd

Examples:

Ex 0: Documentation

Return a shallow copy of the set.



The following table lists operations available for set that do not apply to immutable instances of frozenset:

update(*others) (alternative form: set |= other | ...)

Description: tbd

Examples:

Ex 0: Documentation

Update the set, adding elements from all others.



intersection_update(*others) (alternative form: set &= other & ...)

Description: tbd

Examples:

Ex 0: Documentation

Update the set, keeping only elements found in it and all others.



difference_update(*others) (alternative form: set -= other | ...)

Description: tbd

Examples:

Ex 0: Documentation

Update the set, removing elements found in others.



symmetric_difference_update(other) (alternative form: set ^= other)

Description: tbd

Examples:

Ex 0: Documentation

Update the set, keeping only elements found in either set, but not in both.



add(elem)

Description: tbd

Examples:

Ex 0: Documentation

Add element elem to the set.



remove(elem)

Description: tbd

Examples:

Ex 0: Documentation

Remove element elem from the set. Raises KeyError if elem is not contained in the set.



discard(elem)

Description: tbd

Examples:

Ex 0: Documentation

Remove element elem from the set if it is present.



pop()

Description: tbd

Examples:

Ex 0: Documentation

Remove and return an arbitrary element from the set. Raises KeyError if the set is empty.



clear()

Description: tbd

Examples:

Ex 0: Documentation

Remove all elements from the set.



File Methods

Overview

See [1] for for a nice reference (mostly reproduced below). Also see the Python docs on the io module (core tools for working with streams).

The built-in open() function creates a file object, the most common interface to external files. File objects export the data transfer methods in the following sections, where file content is represented as Python strings. This is a partial list: see Python manuals for lesser-used calls and attributes.

In Python 2.X only, the name file() can be used as a synonym for open() when creating a file object, but open() is the generally recommended spelling. In Python 3.X, file() is no longer available. (The io module's classes are used for file customization.)


File Context Managers and File Usage Notes

In standard Python (CPython), file objects normally close themselves when garbage collected if still open. Because of this, temporary files (e.g., open('name').read()) suffice and need not be closed explicitly, as the file object is immediately reclaimed and closed. Other Python implementations (e.g., Jython), however, may collect and close files less deterministically. To guarantee closes after a block of code exits, regardless of whether the block raises an exception, use the try/finally statement and manual closes:

myfile = open(r'C:\misc\script', 'w')
try:
...use myfile...
finally:
myfile.close()

Or use the with/as statement available in Python 3.X and 2.X (as of 2.6 and 3.0):

with open(r'C:\misc\script', 'w') as myfile:
...use myfile...

The first of these inserts a close call as a termination-time action. The latter employs file object context managers, which guarantee that a file is automatically closed when the enclosed code block exits.

Some general file usage notes:

  • Some file-open modes (e.g., 'r+') allow a file to be both input and output, and others (e.g., 'rb') specify binary-mode transfer to suppress line-end marker conversions (and Unicode encodings in Python 3.X).
  • File-transfer operations occur at the current file position, but seek() method calls reposition the file for random access.
  • File transfers can be made unbuffered: see open() arguments and the -u command-line flag.

Input Files

infile = open(filename, 'r')

Description: Creates input file object, connected to the named external file.

filename is normally a string (e.g., 'data.txt'), and maps to the current working directory unless it includes a directory path prefix (e.g., r'c:\dir\data.txt'). Argument two gives file mode: 'r' reads text, 'rb' reads binary with no line-break translation. Mode is optional and defaults to 'r'.

As noted in the docs for open(), the following are the available modes:

CharacterMeaning
ropen for reading (default)
wopen for writing, truncating the file first
xopen for exclusive creation, failing if the file already exists
aopen for writing, appending to the end of the file if it exists
bbinary mode
ttext mode (default)
+open for updating (reading and writing)

Python 3.X's open() also accepts an optional Unicode encoding name in text mode; 2.X's codecs.open() has similar tools.


infile.read()

Description: Returns the file content.

Reads entire file, returning its contents as a single string. In text mode ('r'), line-ends are translated to '\n' by default. In binary mode ('rb'), the result string can contain nonprintable characters (e.g., '\0'). In Python 3.X, text mode decodes Unicode text into a str string, and binary mode returns unaltered content in a bytes string.


infile.read(N)

Description: Reads at most N more bytes (1 or more); empty at end-offile.


infile.readline()

Description: Reads next line (through end-of-line marker); empty at end-of-file.


infile.readlines()

Description: Reads entire file into a list of line strings. See also the file object's line iterator alternative, discussed in the next list item.


for line in infile

Description: Step through the lines in a file automatically.

This syntax uses the line iterator of file object infile to step through lines in the file automatically. Available in all iteration contexts, including for loops, map(), and comprehensions (e.g., [line.rstrip() for line in open('filename')]). The iteration for line in infile has an effect similar to for line in infile.readlines(), but the line iterator version fetches lines on demand instead of loading the entire file into memory, and so is more space-efficient.


Output Files

outfile = open(filename, 'w')

Description: Creates output file object, connected to external file.

Creates output file object, connected to external file named by filename (defined in the preceding section). Mode 'w' writes text, 'wb' writes binary data with no line-break translation. Python 3.X's open() also accepts an optional Unicode encoding name in text mode; 2.X's codecs.open() has similar tools.


outfile.write(S)

Description: Write the string S to the stream and return the number of characters written.

Writes all content in string S onto file, with no formatting applied. In text mode, '\n' is translated to the platform-specific line-end marker sequence by default. In binary mode, the string can contain nonprintable bytes (e.g., use 'a\0b\0c' to write a string of five bytes, two of which are binary zero). In Python 3.X, text mode requires str Unicode strings and encodes them when written, and binary mode expects and writes bytes strings unaltered.


outfile.writelines(I)

Description: Writes a list of strings to the file.

Writes all strings in iterable I onto file, not adding any lineend characters automatically.


Any Files

file.close()

Description: Closes the file.

Manual close to free resources (although CPython currently auto-closes files if still open when they are garbage collected).


file.tell()

Description: Returns the file's current position.


file.seek(offset [, whence])

Description: Change the file position.

Sets the current file position to offset for random access. whence can be 0 (offset from front), 1 (offset +/– from current position), or 2 (offset from end). whence defaults to 0.


file.isatty()

Description: Returns whether the file stream is interactive or not.

Returns True if the file is connected to a tty-like (interactive) device, else False (may return 1 or 0 in older Python versions).


file.flush()

Description: Flushes the internal buffer.

Flushes the file's stdio buffer. Useful for buffered pipes, if another process (or human) is reading. Also useful for files created and read in the same process.


file.truncate([size])

Description: Resizes the file to a specified size.

Truncates file to, at most, size bytes (or current position if no size is passed). Not available on all platforms.


file.fileno()

Description: Returns a number that represents the stream, from the operating system's perspective.

Gets file number (file descriptor integer) for file. This roughly converts file objects to file descriptors that can be passed to tools in the os module. Hint: use os.fdopen() or 3.X's open() to convert a file descriptor to a file object.


Other File Methods/Attributes

file.readable()

Description: Returns whether the file stream can be read or not.

Return True if the stream can be read from. If False, read() will raise OSError.


file.writable()

Description: Returns whether the file can be written to or not.

Return True if the stream supports writing. If False, write() and truncate() will raise OSError.


file.seekable()

Description: Returns whether the file allows us to change the file position.

Return True if the stream supports random access. If False, seek(), tell() and truncate() will raise OSError.


file.closed

Description: True if file has been closed

True if the stream is closed.


file.mode

Description: Mode string (e.g., 'r') passed to open() function.

The mode as given in the constructor.


file.name

Description: String name of corresponding external file.

The file name. This is the file descriptor of the file when no name is given in the constructor.