Python Language Notes (Overview)
Quick Reference Links
- Index of Python Enhancement Proposals (PEPs)
- The Python Module Index
- The Python Standard Library
- Python Package Index
- Python Time Complexity Wiki
- The Python Tutorial
- Python ZTM Cheatsheet
- Python Monthly
- Python 2.7x vs Python 3.x: Key Differences (short)
- Python 2.7x vs Python 3.x: Key Differences (long)
- Functional Programming
- Iteration and Generators
- Hash Maps
- Object-oriented programming (OOP)
External modules
A listing of frequently used external Python modules (list updated as needed):
Module | Description |
---|---|
tbd | desc |
Standard library modules
A listing of frequently used standard library Python modules (list updated as needed):
Module | Description |
---|---|
Data Structures and Algorithms | |
collections | Container datatypes |
functools | Higher-order functions and operations on callable objects |
itertools | Functions creating iterators for efficient looping |
copy | Shallow and deep copy operations |
json | Encode and decode the JSON format |
json.tool | A command line to validate and pretty-print JSON |
heapq | Heap queue algorithm (a.k.a. priority queue) |
queue | A synchronized queue class |
graphlib | Functionality to operate with graph-like structures |
re | Regular expression operations |
string | Common string operations |
cmath | Mathematical functions for complex numbers |
math | Mathematical functions (sin() etc.) |
random | Generate pseudo-random numbers with various common distributions |
statistics | Mathematical statistics functions |
Dates and Times | |
calendar | Functions for working with calendars, including some emulation of the Unix cal program |
datetime | Basic date and time types |
Debugging and Testing | |
difflib | Helpers for computing differences between objects |
inspect | Extract information and source code from live objects |
logging | Flexible event logging system for applications |
pdb | The Python debugger for interactive interpreters |
time | Time access and conversions |
timeit | Measure the execution time of small code snippets |
unittest | Unit testing framework for Python |
unittest.mock | Mock object library |
warnings | Issue warning messages and control their disposition |
Documentation | |
doctest | Test pieces of code within docstrings |
pydoc | Documentation generator and online help system |
types | Names for built-in types |
typing | Support for type hints (see :pep:484 ) |
Encoding and Decoding | |
base64 | RFC 3548: Base16, Base32, Base64 Data Encodings; Base85 and Ascii85 |
hashlib | Secure hash and message digest algorithms |
uuid | UUID objects (universally unique identifiers) according to RFC 4122 |
File Manipulation and Input/Output | |
asyncio | Asynchronous I/O |
csv | Write and read tabular data to and from delimited files |
io | Core tools for working with streams |
os | Miscellaneous operating system interfaces |
pathlib | Object-oriented filesystem paths |
sys | Access system-specific parameters and functions |
sysconfig | Python's configuration information |
tempfile | Generate temporary files and directories |
textwrap | Text wrapping and filling |
Reference | |
__main__ | The environment where the top-level script is run |
dataclasses | Generate special methods on user-defined classes |
email | Package supporting the parsing, manipulating, and generating email messages |
glob | Unix shell style pathname pattern expansion |
keyword | Test whether a string is a keyword in Python |
venv | Creation of virtual environments |
Complete standard library module index
Module | Description |
---|---|
- | |
__future__ | Future statement definitions |
__main__ | The environment where the top-level script is run |
_thread | Low-level threading API |
A | |
abc | Abstract base classes according to :pep:3119 |
aifc | Read and write audio files in AIFF or AIFC format |
argparse | Command-line option and argument parsing library |
array | Space efficient arrays of uniformly typed numeric values |
ast | Abstract Syntax Tree classes and manipulation |
asynchat | Support for asynchronous command/response protocols |
asyncio | Asynchronous I/O |
asyncore | A base class for developing asynchronous socket handling services |
atexit | Register and execute cleanup functions |
audioop | Manipulate raw audio data |
B | |
base64 | RFC 3548: Base16, Base32, Base64 Data Encodings; Base85 and Ascii85 |
bdb | Debugger framework |
binascii | Tools for converting between binary and various ASCII-encoded binary representations |
binhex | Encode and decode files in binhex4 format |
bisect | Array bisection algorithms for binary searching |
builtins | The module that provides the built-in namespace |
bz2 | Interfaces for bzip2 compression and decompression |
C | |
calendar | Functions for working with calendars, including some emulation of the Unix cal program |
cgi | Helpers for running Python scripts via the Common Gateway Interface |
cgitb | Configurable traceback handler for CGI scripts |
chunk | Module to read IFF chunks |
cmath | Mathematical functions for complex numbers |
cmd | Build line-oriented command interpreters |
code | Facilities to implement read-eval-print loops |
codecs | Encode and decode data and streams |
codeop | Compile (possibly incomplete) Python code |
collections | Container datatypes |
collections.abc | Abstract base classes for containers |
colorsys | Conversion functions between RGB and other color systems |
compileall | Tools for byte-compiling all Python source files in a directory tree |
concurrent | |
concurrent.futures | Execute computations concurrently using threads or processes |
configparser | Configuration file parser |
contextlib | Utilities for with-statement contexts |
contextvars | Context Variables |
copy | Shallow and deep copy operations |
copyreg | Register pickle support functions |
cProfile | |
crypt (Unix) | The crypt() function used to check Unix passwords |
csv | Write and read tabular data to and from delimited files |
ctypes | A foreign function library for Python |
curses (Unix) | An interface to the curses library, providing portable terminal handling |
curses.ascii | Constants and set-membership functions for ASCII characters |
curses.panel | A panel stack extension that adds depth to curses windows |
curses.textpad | Emacs-like input editing in a curses window |
D | |
dataclasses | Generate special methods on user-defined classes |
datetime | Basic date and time types |
dbm | Interfaces to various Unix "database" formats |
dbm.dumb | Portable implementation of the simple DBM interface |
dbm.gnu (Unix) | GNU's reinterpretation of dbm |
dbm.ndbm (Unix) | The standard "database" interface, based on ndbm |
decimal | Implementation of the General Decimal Arithmetic Specification |
difflib | Helpers for computing differences between objects |
dis | Disassembler for Python bytecode |
distutils | Support for building and installing Python modules into an existing Python installation |
distutils.archive_util | Utility functions for creating archive files (tarballs, zip files, ...) |
distutils.bcppcompiler | |
distutils.ccompiler | Abstract CCompiler class |
distutils.cmd | Provides the abstract base class :class:~distutils.cmd.Command . This class is subclassed by the modules in the distutils.command subpackage. |
distutils.command | Contains one module for each standard Distutils command |
distutils.command.bdist | Build a binary installer for a package |
distutils.command.bdist_dumb | Build a "dumb" installer - a simple archive of files |
distutils.command.bdist_msi | Build a binary distribution as a Windows MSI file |
distutils.command.bdist_packager | Abstract base class for packagers |
distutils.command.bdist_rpm | Build a binary distribution as a Redhat RPM and SRPM |
distutils.command.bdist_wininst | Build a Windows installer |
distutils.command.build | Build all files of a package |
distutils.command.build_clib | Build any C libraries in a package |
distutils.command.build_ext | Build any extensions in a package |
distutils.command.build_py | Build the .py/.pyc files of a package |
distutils.command.build_scripts | Build the scripts of a package |
distutils.command.check | Check the meta-data of a package |
distutils.command.clean | Clean a package build area |
distutils.command.config | Perform package configuration |
distutils.command.install | Install a package |
distutils.command.install_data | Install data files from a package |
distutils.command.install_headers | Install C/C++ header files from a package |
distutils.command.install_lib | Install library files from a package |
distutils.command.install_scripts | Install script files from a package |
distutils.command.register | Register a module with the Python Package Index |
distutils.command.sdist | Build a source distribution |
distutils.core | The core Distutils functionality |
distutils.cygwinccompiler | |
distutils.debug | Provides the debug flag for distutils |
distutils.dep_util | Utility functions for simple dependency checking |
distutils.dir_util | Utility functions for operating on directories and directory trees |
distutils.dist | Provides the Distribution class, which represents the module distribution being built/installed/distributed |
distutils.errors | Provides standard distutils exceptions |
distutils.extension | Provides the Extension class, used to describe C/C++ extension modules in setup scripts |
distutils.fancy_getopt | Additional getopt functionality |
distutils.file_util | Utility functions for operating on single files |
distutils.filelist | The FileList class, used for poking about the file system and building lists of files. |
distutils.log | A simple logging mechanism, :pep:282 -style |
distutils.msvccompiler | Microsoft Compiler |
distutils.spawn | Provides the spawn() function |
distutils.sysconfig | Low-level access to configuration information of the Python interpreter |
distutils.text_file | Provides the TextFile class, a simple interface to text files |
distutils.unixccompiler | UNIX C Compiler |
distutils.util | Miscellaneous other utility functions |
distutils.version | Implements classes that represent module version numbers |
doctest | Test pieces of code within docstrings |
E | |
email | Package supporting the parsing, manipulating, and generating email messages |
email.charset | Character Sets |
email.contentmanager | Storing and Retrieving Content from MIME Parts |
email.encoders | Encoders for email message payloads |
email.errors | The exception classes used by the email package |
email.generator | Generate flat text email messages from a message structure |
email.header | Representing non-ASCII headers |
email.headerregistry | Automatic Parsing of headers based on the field name |
email.iterators | Iterate over a message object tree |
email.message | The base class representing email messages |
email.mime | Build MIME messages |
email.parser | Parse flat text email messages to produce a message object structure |
email.policy | Controlling the parsing and generating of messages |
email.utils | Miscellaneous email package utilities |
encodings | |
encodings.idna | Internationalized Domain Names implementation |
encodings.mbcs | Windows ANSI codepage |
encodings.utf_8_sig | UTF-8 codec with BOM signature |
ensurepip | Bootstrapping the "pip" installer into an existing Python installation or virtual environment |
enum | Implementation of an enumeration class |
errno | Standard errno system symbols |
F | |
faulthandler | Dump the Python traceback |
fcntl (Unix) | The fcntl() and ioctl() system calls |
filecmp | Compare files efficiently |
fileinput | Loop over standard input or a list of files |
fnmatch | Unix shell style filename pattern matching |
formatter | Deprecated: Generic output formatter and device interface |
fractions | Rational numbers |
ftplib | FTP protocol client (requires sockets) |
functools | Higher-order functions and operations on callable objects |
G | |
gc | Interface to the cycle-detecting garbage collector |
getopt | Portable parser for command line options; support both short and long option names |
getpass | Portable reading of passwords and retrieval of the userid |
gettext | Multilingual internationalization services |
glob | Unix shell style pathname pattern expansion |
graphlib | Functionality to operate with graph-like structures |
grp (Unix) | The group database (getgrnam() and friends) |
gzip | Interfaces for gzip compression and decompression using file objects |
H | |
hashlib | Secure hash and message digest algorithms |
heapq | Heap queue algorithm (a.k.a. priority queue) |
hmac | Keyed-Hashing for Message Authentication (HMAC) implementation |
html | Helpers for manipulating HTML |
html.entities | Definitions of HTML general entities |
html.parser | A simple parser that can handle HTML and XHTML |
http | HTTP status codes and messages |
http.client | HTTP and HTTPS protocol client (requires sockets) |
http.cookiejar | Classes for automatic handling of HTTP cookies |
http.cookies | Support for HTTP state management (cookies) |
http.server | HTTP server and request handlers |
I | |
imaplib | IMAP4 protocol client (requires sockets) |
imghdr | Determine the type of image contained in a file or byte stream |
imp | Deprecated: Access the implementation of the import statement |
importlib | The implementation of the import machinery |
importlib.abc | Abstract base classes related to import |
importlib.machinery | Importers and path hooks |
importlib.metadata | The implementation of the importlib metadata |
importlib.resources | Package resource reading, opening, and access |
importlib.util | Utility code for importers |
inspect | Extract information and source code from live objects |
io | Core tools for working with streams |
ipaddress | IPv4/IPv6 manipulation library |
itertools | Functions creating iterators for efficient looping |
J | |
json | Encode and decode the JSON format |
json.tool | A command line to validate and pretty-print JSON |
K | |
keyword | Test whether a string is a keyword in Python |
L | |
lib2to3 | The 2to3 library |
linecache | Provides random access to individual lines from text files |
locale | Internationalization services |
logging | Flexible event logging system for applications |
logging.config | Configuration of the logging module |
logging.handlers | Handlers for the logging module |
lzma | A Python wrapper for the liblzma compression library |
M | |
mailbox | Manipulate mailboxes in various formats |
mailcap | Mailcap file handling |
marshal | Convert Python objects to streams of bytes and back (with different constraints) |
math | Mathematical functions (sin() etc.) |
mimetypes | Mapping of filename extensions to MIME types |
mmap | Interface to memory-mapped files for Unix and Windows |
modulefinder | Find 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 |
multiprocessing | Process-based parallelism |
multiprocessing.connection | API for dealing with sockets |
multiprocessing.dummy | Dumb wrapper around threading |
multiprocessing.managers | Share data between process with shared objects |
multiprocessing.pool | Create pools of processes |
multiprocessing.shared_memory | Provides shared memory for direct access across processes |
multiprocessing.sharedctypes | Allocate ctypes objects from shared memory |
N | |
netrc | Loading of .netrc files |
nis (Unix) | Interface to Sun's NIS (Yellow Pages) library |
nntplib | NNTP protocol client (requires sockets) |
numbers | Numeric abstract base classes (Complex, Real, Integral, etc.) |
O | |
operator | Functions corresponding to the standard operators |
optparse | Deprecated: Command-line option parsing library |
os | Miscellaneous operating system interfaces |
os.path | Operations on pathnames |
ossaudiodev | (Linux, FreeBSD) Access to OSS-compatible audio devices |
P | |
parser | Access parse trees for Python source code |
pathlib | Object-oriented filesystem paths |
pdb | The Python debugger for interactive interpreters |
pickle | Convert Python objects to streams of bytes and back |
pickletools | Contains 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 |
pkgutil | Utilities for the import system |
platform | Retrieves as much platform identifying data as possible |
plistlib | Generate and parse Apple plist files |
poplib | POP3 protocol client (requires sockets) |
posix (Unix) | The most common POSIX system calls (normally used via module os) |
pprint | Data pretty printer |
profile | Python source profiler |
pstats | Statistics object for use with the profiler |
pty (Linux) | Pseudo-Terminal Handling for Linux |
pwd (Unix) | The password database (getpwnam() and friends) |
py_compile | Generate byte-code files from Python source files |
pyclbr | Supports information extraction for a Python module browser |
pydoc | Documentation generator and online help system |
Q | |
queue | A synchronized queue class |
quopri | Encode and decode files using the MIME quoted-printable encoding |
R | |
random | Generate pseudo-random numbers with various common distributions |
re | Regular expression operations |
readline (Unix) | GNU readline support for Python |
reprlib | Alternate repr() implementation with size limits |
resource (Unix) | An interface to provide resource usage information on the current process |
rlcompleter | Python identifier completion, suitable for the GNU readline library |
runpy | Locate and run Python modules without importing them first |
S | |
sched | General purpose event scheduler |
secrets | Generate secure random numbers for managing secrets |
select | Wait for I/O completion on multiple streams |
selectors | High-level I/O multiplexing |
shelve | Python object persistence |
shlex | Simple lexical analysis for Unix shell-like languages |
shutil | High-level file operations, including copying |
signal | Set handlers for asynchronous events |
site | Module responsible for site-specific configuration |
smtpd | A SMTP server implementation in Python |
smtplib | SMTP protocol client (requires sockets) |
sndhdr | Determine type of a sound file |
socket | Low-level networking interface |
socketserver | A framework for network servers |
spwd (Unix) | The shadow password database (getspnam() and friends) |
sqlite3 | A DB-API 2.0 implementation using SQLite 3.x |
ssl | TLS/SSL wrapper for socket objects |
stat | Utilities for interpreting the results of os.stat(), os.lstat() and os.fstat() |
statistics | Mathematical statistics functions |
string | Common string operations |
stringprep | String preparation, as per RFC 3453 |
struct | Interpret bytes as packed binary data |
subprocess | Subprocess management |
sunau | Provide an interface to the Sun AU sound format |
symbol | Constants representing internal nodes of the parse tree |
symtable | Interface to the compiler's internal symbol tables |
sys | Access system-specific parameters and functions |
sysconfig | Python's configuration information |
syslog (Unix) | An interface to the Unix syslog library routines |
T | |
tabnanny | Tool for detecting white space related problems in Python source files in a directory tree |
tarfile | Read and write tar-format archive files |
telnetlib | Telnet client class |
tempfile | Generate temporary files and directories |
termios (Unix) | POSIX style tty control |
test | Regression tests package containing the testing suite for Python |
test.support | Support for Python's regression test suite |
test.support.bytecode_helper | Support tools for testing correct bytecode generation |
test.support.script_helper | Support for Python's script execution tests |
test.support.socket_helper | Support for socket tests |
textwrap | Text wrapping and filling |
threading | Thread-based parallelism |
time | Time access and conversions |
timeit | Measure the execution time of small code snippets |
tkinter | Interface 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.tix | Tk Extension Widgets for Tkinter |
tkinter.ttk | Tk themed widget set |
token | Constants representing terminal nodes of the parse tree |
tokenize | Lexical scanner for Python source code |
trace | Trace or track Python statement execution |
traceback | Print or retrieve a stack traceback |
tracemalloc | Trace memory allocations |
tty (Unix) | Utility functions that perform common terminal control operations |
turtle | An educational framework for simple graphics applications |
turtledemo | A viewer for example turtle scripts |
types | Names for built-in types |
typing | Support for type hints (see :pep:484 ) |
U | |
unicodedata | Access the Unicode Database |
unittest | Unit testing framework for Python |
unittest.mock | Mock object library |
urllib | |
urllib.error | Exception classes raised by urllib.request |
urllib.parse | Parse URLs into or assemble them from components |
urllib.request | Extensible library for opening URLs |
urllib.response | Response classes used by urllib |
urllib.robotparser | Load a robots.txt file and answer questions about fetchability of other URLs |
uu | Encode and decode files in uuencode format |
uuid | UUID objects (universally unique identifiers) according to RFC 4122 |
V | |
venv | Creation of virtual environments |
W | |
warnings | Issue warning messages and control their disposition |
wave | Provide an interface to the WAV sound format |
weakref | Support for weak references and weak dictionaries |
webbrowser | Easy-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 |
wsgiref | WSGI Utilities and Reference Implementation |
wsgiref.handlers | WSGI server/gateway base classes |
wsgiref.headers | WSGI response header tools |
wsgiref.simple_server | A simple WSGI HTTP server |
wsgiref.util | WSGI environment utilities |
wsgiref.validate | WSGI conformance checker |
X | |
xdrlib | Encoders and decoders for the External Data Representation (XDR) |
xml | Package containing XML processing modules |
xml.dom | Document Object Model API for Python |
xml.dom.minidom | Minimal Document Object Model (DOM) implementation |
xml.dom.pulldom | Support for building partial DOM trees from SAX events |
xml.etree.ElementTree | Implementation of the ElementTree API |
xml.parsers.expat | An interface to the Expat non-validating XML parser |
xml.parsers.expat.errors | |
xml.parsers.expat.model | |
xml.sax | Package containing SAX2 base classes and convenience functions |
xml.sax.handler | Base classes for SAX event handlers |
xml.sax.saxutils | Convenience functions and classes for use with SAX |
xml.sax.xmlreader | Interface which SAX-compliant XML parsers must implement |
xmlrpc | |
xmlrpc.client | XML-RPC client access |
xmlrpc.server | Basic XML-RPC server implementations |
Z | |
zipapp | Manage executable Python zip archives |
zipfile | Read and write ZIP-format archive files |
zipimport | Support for importing Python modules from ZIP archives |
zlib | Low-level interface to compression and decompression routines compatible with gzip |
zoneinfo | IANA time zone support |
W3 general reference links with descriptions
Built-in functions
Function | Description |
---|---|
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
Method | Description |
---|---|
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
Method | Description |
---|---|
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
Method | Description |
---|---|
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
Method | Description |
---|---|
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
Method | Description |
---|---|
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
Method | Description |
---|---|
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
Keyword | Description |
---|---|
and | A logical operator |
as | To create an alias |
assert | For debugging |
break | To break out of a loop |
class | To define a class |
continue | To continue to the next iteration of a loop |
def | To define a function |
del | To delete an object |
elif | Used in conditional statements, same as else if |
else | Used in conditional statements |
except | Used with exceptions, what to do when an exception occurs |
False | Boolean value, result of comparison operations |
finally | Used with exceptions, a block of code that will be executed no matter if there is an exception or not |
for | To create a for loop |
from | To import specific parts of a module |
global | To declare a global variable |
if | To make a conditional statement |
import | To import a module |
in | To check if a value is present in a list, tuple, etc. |
is | To test if two variables are equal |
lambda | To create an anonymous function |
None | Represents a null value |
nonlocal | To declare a non-local variable |
not | A logical operator |
or | A logical operator |
pass | A null statement, a statement that will do nothing |
raise | To raise an exception |
return | To exit a function and return a value |
True | Boolean value, result of comparison operations |
try | To make a try...except statement |
while | To create a while loop |
with | Used to simplify exception handling |
yield | To end a function, returns a generator |
Exceptions
Exception | Description |
---|---|
ArithmeticError | Raised when an error occurs in numeric calculations |
AssertionError | Raised when an assert statement fails |
AttributeError | Raised when attribute reference or assignment fails |
Exception | Base class for all exceptions |
EOFError | Raised when the input() method hits an "end of file" condition (EOF) |
FloatingPointError | Raised when a floating point calculation fails |
GeneratorExit | Raised when a generator is closed (with the close() method) |
ImportError | Raised when an imported module does not exist |
IndentationError | Raised when indendation is not correct |
IndexError | Raised when an index of a sequence does not exist |
KeyError | Raised when a key does not exist in a dictionary |
KeyboardInterrupt | Raised when the user presses Ctrl+c, Ctrl+z or Delete |
LookupError | Raised when errors raised cant be found |
MemoryError | Raised when a program runs out of memory |
NameError | Raised when a variable does not exist |
NotImplementedError | Raised when an abstract method requires an inherited class to override the method |
OSError | Raised when a system related operation causes an error |
OverflowError | Raised when the result of a numeric calculation is too large |
ReferenceError | Raised when a weak reference object does not exist |
RuntimeError | Raised when an error occurs that do not belong to any specific expections |
StopIteration | Raised when the next() method of an iterator has no further values |
SyntaxError | Raised when a syntax error occurs |
TabError | Raised when indentation consists of tabs or spaces |
SystemError | Raised when a system error occurs |
SystemExit | Raised when the sys.exit() function is called |
TypeError | Raised when two different types are combined |
UnboundLocalError | Raised when a local variable is referenced before assignment |
UnicodeError | Raised when a unicode problem occurs |
UnicodeEncodeError | Raised when a unicode encoding problem occurs |
UnicodeDecodeError | Raised when a unicode decoding problem occurs |
UnicodeTranslateError | Raised when a unicode translation problem occurs |
ValueError | Raised when there is a wrong value in a specified data type |
ZeroDivisionError | Raised when the second operator in a division is zero |
Glossary
Feature | Description |
---|---|
Indentation | Indentation refers to the spaces at the beginning of a code line |
Comments | Comments are code lines that will not be executed |
Multi Line Comments | How to insert comments on multiple lines |
Creating Variables | Variables are containers for storing data values |
Variable Names | How to name your variables |
Assign Values to Multiple Variables | How to assign values to multiple variables |
Output Variables | Use the print statement to output variables |
String Concatenation | How to combine strings |
Global Variables | Global variables are variables that belongs to the global scope |
Built-In Data Types | Python has a set of built-in data types |
Getting Data Type | How to get the data type of an object |
Setting Data Type | How to set the data type of an object |
Numbers | There are three numeric types in Python |
Int | The integer number type |
Float | The floating number type |
Complex | The complex number type |
Type Conversion | How to convert from one number type to another |
Random Number | How to create a random number |
Specify a Variable Type | How to specify a certain data type for a variable |
String Literals | How to create string literals |
Assigning a String to a Variable | How to assign a string value to a variable |
Multiline Strings | How to create a multi line string |
Strings are Arrays | Strings in Python are arrays of bytes representing Unicode characters |
Slicing a String | How to slice a string |
Negative Indexing on a String | How to use negative indexing when accessing a string |
String Length | How to get the length of a string |
Check In String | How to check if a string contains a specified phrase |
Format String | How to combine two strings |
Escape Characters | How to use escape characters |
Boolean Values | True or False |
Evaluate Booleans | Evaluate a value or statement and return either True or False |
Return Boolean Value | Functions that return a Boolean value |
Operators | Use operator to perform operations in Python |
Arithmetic Operators | Arithmetic operator are used to perform common mathematical operations |
Assignment Operators | Assignment operators are use to assign values to variables |
Comparison Operators | Comparison operators are used to compare two values |
Logical Operators | Logical operators are used to combine conditional statements |
Identity Operators | Identity operators are used to see if two objects are in fact the same object |
Membership Operators | Membership operators are used to test is a sequence is present in an object |
Bitwise Operators | Bitwise operators are used to compare (binary) numbers |
Lists | A list is an ordered, and changeable, collection |
Access List Items | How to access items in a list |
Change List Item | How to change the value of a list item |
Loop Through List Items | How to loop through the items in a list |
List Comprehension | How use a list comprehensive |
Check if List Item Exists | How to check if a specified item is present in a list |
List Length | How to determine the length of a list |
Add List Items | How to add items to a list |
Remove List Items | How to remove list items |
Copy a List | How to copy a list |
Join Two Lists | How to join two lists |
Tuple | A tuple is an ordered, and unchangeable, collection |
Access Tuple Items | How to access items in a tuple |
Change Tuple Item | How to change the value of a tuple item |
Loop List Items | How to loop through the items in a tuple |
Check if Tuple Item Exists | How to check if a specified item is present in a tuple |
Tuple Length | How to determine the length of a tuple |
Tuple With One Item | How to create a tuple with only one item |
Remove Tuple Items | How to remove tuple items |
Join Two Tuples | How to join two tuples |
Set | A set is an unordered, and unchangeable, collection |
Access Set Items | How to access items in a set |
Add Set Items | How to add items to a set |
Loop Set Items | DETTE KAPITTELET MANGLER |
Check if Set Item Exists | DETTE KAPITTELET MANGLER |
Set Length | How to determine the length of a set |
Remove Set Items | How to remove set items |
Join Two Sets | How to join two sets |
Dictionary | A dictionary is an unordered, and changeable, collection |
Access Dictionary Items | How to access items in a dictionary |
Change Dictionary Item | How to change the value of a dictionary item |
Loop Dictionary Items | How to loop through the items in a tuple |
Check if Dictionary Item Exists | How to check if a specified item is present in a dictionary |
Dictionary Length | How to determine the length of a dictionary |
Add Dictionary Item | How to add an item to a dictionary |
Remove Dictionary Items | How to remove dictionary items |
Copy Dictionary | How to copy a dictionary |
Nested Dictionaries | A dictionary within a dictionary |
If Statement | How to write an if statement |
If Indentation | If statemnts in Python relies on indentation (whitespace at the beginning of a line) |
Elif | elif is the same as "else if" in other programming languages |
Else | How to write an if...else statement |
Shorthand If | How to write an if statement in one line |
Shorthand If Else | How to write an if...else statement in one line |
If AND | Use the and keyword to combine if statements |
If OR | Use the or keyword to combine if statements |
Nested If | How to write an if statement inside an if statement |
The pass Keyword in If | Use the pass keyword inside empty if statements |
While | How to write a while loop |
While Break | How to break a while loop |
While Continue | How to stop the current iteration and continue wit the next |
While Else | How to use an else statement in a while loop |
For | How to write a for loop |
Loop Through a String | How to loop through a string |
For Break | How to break a for loop |
For Continue | How to stop the current iteration and continue wit the next |
Looping Through a rangee | How to loop through a range of values |
For Else | How to use an else statement in a for loop |
Nested Loops | How to write a loop inside a loop |
For pass | Use the pass keyword inside empty for loops |
Function | How to create a function in Python |
Call a Function | How to call a function in Python |
Function Arguments | How to use arguments in a function |
*args | To deal with an unknown number of arguments in a function, use the * symbol before the parameter name |
Keyword Arguments | How to use keyword arguments in a function |
*kwargs | To deal with an unknown number of keyword arguments in a function, use the * symbol before the parameter name |
Default Parameter Value | How to use a default parameter value |
Passing a List as an Argument | How to pass a list as an argument |
Function Return Value | How to return a value from a function |
The pass Statement i Functions | Use the pass statement in empty functions |
Function Recursion | Functions that can call itself is called recursive functions |
Lambda Function | How to create anonymous functions in Python |
Why Use Lambda Functions | Learn when to use a lambda function or not |
Array | Lists can be used as Arrays |
What is an Array | Arrays are variables that can hold more than one value |
Access Arrays | How to access array items |
Array Length | How to get the length of an array |
Looping Array Elements | How to loop through array elements |
Add Array Element | How to add elements from an array |
Remove Array Element | How to remove elements from an array |
Array Methods | Python has a set of Array/Lists methods |
Class | A class is like an object constructor |
Create Class | How to create a class |
The Class init() Function | The init() function is executed when the class is initiated |
Object Methods | Methods in objects are functions that belongs to the object |
self | The self parameter refers to the current instance of the class |
Modify Object Properties | How to modify properties of an object |
Delete Object Properties | How to modify properties of an object |
Delete Object | How to delete an object |
Class pass Statement | Use the pass statement in empty classes |
Create Parent Class | How to create a parent class |
Create Child Class | How to create a child class |
Create the init() Function | How to create the init() function |
super Function | The super() function make the child class inherit the parent class |
Add Class Properties | How to add a property to a class |
Add Class Methods | How to add a method to a class |
Iterators | An iterator is an object that contains a countable number of values |
Iterator vs Iterable | What is the difference between an iterator and an iterable |
Loop Through an Iterator | How to loop through the elements of an iterator |
Create an Iterator | How to create an iterator |
StopIteration | How to stop an iterator |
Global Scope | When does a variable belong to the global scope? |
Global Keyword | The global keyword makes the variable global |
Create a Module | How to create a module |
Variables in Modules | How to use variables in a module |
Renaming a Module | How to rename a module |
Built-in Modules | How to import built-in modules |
Using the dir() Function | List all variable names and function names in a module |
Import From Module | How to import only parts from a module |
Datetime Module | How to work with dates in Python |
Date Output | How to output a date |
Create a Date Object | How to create a date object |
The strftime Method | How to format a date object into a readable string |
Date Format Codes | The datetime module has a set of legal format codes |
JSON | How to work with JSON in Python |
Parse JSON | How to parse JSON code in Python |
Convert into JSON | How to convert a Python object in to JSON |
Format JSON | How to format JSON output with indentations and line breaks |
Sort JSON | How to sort JSON |
RegEx Module | How to import the regex module |
RegEx Functions | The re module has a set of functions |
Metacharacters in RegEx | Metacharacters are characters with a special meaning |
RegEx Special Sequences | A backslash followed by a a character has a special meaning |
RegEx Sets | A set is a set of characters inside a pair of square brackets with a special meaning |
RegEx Match Object | The Match Object is an object containing information about the search and the result |
Install PIP | How to install PIP |
PIP Packages | How to download and install a package with PIP |
PIP Remove Package | How to remove a package with PIP |
Error Handling | How to handle errors in Python |
Handle Many Exceptions | How to handle more than one exception |
Try Else | How to use the else keyword in a try statement |
Try Finally | How to use the finally keyword in a try statement |
raise | How to raise an exception in Python |
W3 School Python module reference with descriptions
Random module
Method | Description |
---|---|
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
Method | Description |
---|---|
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
Method | Description |
---|---|
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
Method | Description |
---|---|
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.e | Returns Euler's number (2.7182...) |
math.inf | Returns a floating-point positive infinity |
math.nan | Returns a floating-point NaN (Not a Number) value |
math.pi | Returns PI (3.1415...) |
math.tau | Returns tau (6.2831...) |
cMath module
Method | Description |
---|---|
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.e | Returns Euler's number (2.7182...) |
cmath.inf | Returns a floating-point positive infinity value |
cmath.infj | Returns a complex infinity value |
cmath.nan | Returns floating-point NaN (Not a Number) value |
cmath.nanj | Returns coplext NaN (Not a Number) value |
cmath.pi | Returns PI (3.1415...) |
cmath.tau | Returns 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.
Operation | Result | Notes |
---|---|---|
x in s | True if an item of s is equal to x , else False | (1) |
x not in s | False if an item of s is equal to x , else True | (1) |
s + t | the concatenation of s and t | (6)(7) |
s * n or n * s | equivalent 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 usestr.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 usebytes.join()
or io.BytesIO, or you can do in-place concatenation with abytearray
object.bytearray
objects are mutable and have an efficient overallocation mechanism - if concatenating
tuple
objects, extend alist
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
).
Operation | Result | Notes |
---|---|---|
s[i] = x | item i of s is replaced by x | |
s[i:j] = t | slice 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] = t | the 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 += t | extends s with the contents of t (for the most part the same as s[len(s):len(s)] = t ) | |
s *= n | updates 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 strb''
- an empty bytesset()
- an empty set- an empty range, like
range(0)
- objects for which
obj.__bool__()
returnsFalse
obj.__len__()
returns0
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 of32
(i.e.,ord(' ')
returns32
).''
: This is true because the iterable''
is empty. Hence, when the functional equivalent ofall()
def all(iterable):
for element in iterable:
if not element:
return False
return Trueis executed, the
for
loop never runs andTrue
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 trueFalse
- 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 strb''
- an empty bytesset()
- an empty set- an empty range, like
range(0)
- objects for which
obj.__bool__()
returnsFalse
obj.__len__()
returns0
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
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 falseTrue
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 strb''
- an empty bytesset()
- an empty set- an empty range, like
range(0)
- objects for which
obj.__bool__()
returnsFalse
obj.__len__()
returns0
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 ofbytes
.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
andbytearray
do not support Unicode encoding (they are raw bytes, including both media and already encoded text), but may be decoded tostr
.bytes
andbytearray
do not support string formatting (implemented bystr.format
).bytearray
has extra mutable in-place methods and operators similar tolist
(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:
Type | Description |
---|---|
String | Converts the string to bytes using str.encode() . Must also provide encoding and optionally errors |
Integer | Creates an array of provided size, all initialized to null |
Object | A read-only buffer of the object will be used to initialize the byte array |
Iterable | Creates 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 usingstr.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:
Type | Description |
---|---|
String | Converts the string to bytes using str.encode() . Must also provide encoding and optionally errors |
Integer | Creates an array of provided size, all initialized to null |
Object | A read-only buffer of the object will be used to initialize the byte array |
Iterable | Creates 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 callableFalse
- 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
Dec | Hex | Oct | Binary | HTML | Char | Description |
---|---|---|---|---|---|---|
0 | 00 | 000 | 00000000 | � | NUL | Null |
1 | 01 | 001 | 00000001 |  | SOH | Start of Header |
2 | 02 | 002 | 00000010 |  | STX | Start of Text |
3 | 03 | 003 | 00000011 |  | ETX | End of Text |
4 | 04 | 004 | 00000100 |  | EOT | End of Transmission |
5 | 05 | 005 | 00000101 |  | ENQ | Enquiry |
6 | 06 | 006 | 00000110 |  | ACK | Acknowledge |
7 | 07 | 007 | 00000111 |  | BEL | Bell |
8 | 08 | 010 | 00001000 |  | BS | Backspace |
9 | 09 | 011 | 00001001 | 	 | HT | Horizontal Tab |
10 | 0A | 012 | 00001010 | | LF | Line Feed |
11 | 0B | 013 | 00001011 |  | VT | Vertical Tab |
12 | 0C | 014 | 00001100 |  | FF | Form Feed |
13 | 0D | 015 | 00001101 | | CR | Carriage Return |
14 | 0E | 016 | 00001110 |  | SO | Shift Out |
15 | 0F | 017 | 00001111 |  | SI | Shift In |
16 | 10 | 020 | 00010000 |  | DLE | Data Link Escape |
17 | 11 | 021 | 00010001 |  | DC1 | Device Control 1 |
18 | 12 | 022 | 00010010 |  | DC2 | Device Control 2 |
19 | 13 | 023 | 00010011 |  | DC3 | Device Control 3 |
20 | 14 | 024 | 00010100 |  | DC4 | Device Control 4 |
21 | 15 | 025 | 00010101 |  | NAK | Negative Acknowledge |
22 | 16 | 026 | 00010110 |  | SYN | Synchronize |
23 | 17 | 027 | 00010111 |  | ETB | End of Transmission Block |
24 | 18 | 030 | 00011000 |  | CAN | Cancel |
25 | 19 | 031 | 00011001 |  | EM | End of Medium |
26 | 1A | 032 | 00011010 |  | SUB | Substitute |
27 | 1B | 033 | 00011011 |  | ESC | Escape |
28 | 1C | 034 | 00011100 |  | FS | File Separator |
29 | 1D | 035 | 00011101 |  | GS | Group Separator |
30 | 1E | 036 | 00011110 |  | RS | Record Separator |
31 | 1F | 037 | 00011111 |  | US | Unit Separator |
32 | 20 | 040 | 00100000 |   | space | Space |
33 | 21 | 041 | 00100001 | ! | ! | exclamation mark |
34 | 22 | 042 | 00100010 | " | " | double quote |
35 | 23 | 043 | 00100011 | # | # | number |
36 | 24 | 044 | 00100100 | $ | $ | dollar |
37 | 25 | 045 | 00100101 | % | % | percent |
38 | 26 | 046 | 00100110 | & | & | ampersand |
39 | 27 | 047 | 00100111 | ' | ' | single quote |
40 | 28 | 050 | 00101000 | ( | ( | left parenthesis |
41 | 29 | 051 | 00101001 | ) | ) | right parenthesis |
42 | 2A | 052 | 00101010 | * | * | asterisk |
43 | 2B | 053 | 00101011 | + | + | plus |
44 | 2C | 054 | 00101100 | , | , | comma |
45 | 2D | 055 | 00101101 | - | - | minus |
46 | 2E | 056 | 00101110 | . | . | period |
47 | 2F | 057 | 00101111 | / | / | slash |
48 | 30 | 060 | 00110000 | 0 | 0 | zero |
49 | 31 | 061 | 00110001 | 1 | 1 | one |
50 | 32 | 062 | 00110010 | 2 | 2 | two |
51 | 33 | 063 | 00110011 | 3 | 3 | three |
52 | 34 | 064 | 00110100 | 4 | 4 | four |
53 | 35 | 065 | 00110101 | 5 | 5 | five |
54 | 36 | 066 | 00110110 | 6 | 6 | six |
55 | 37 | 067 | 00110111 | 7 | 7 | seven |
56 | 38 | 070 | 00111000 | 8 | 8 | eight |
57 | 39 | 071 | 00111001 | 9 | 9 | nine |
58 | 3A | 072 | 00111010 | : | : | colon |
59 | 3B | 073 | 00111011 | ; | ; | |
60 | 3C | 074 | 00111100 | < | < | less than |
61 | 3D | 075 | 00111101 | = | = | equality sign |
62 | 3E | 076 | 00111110 | > | > | greater than |
63 | 3F | 077 | 00111111 | ? | ? | question mark |
64 | 40 | 100 | 01000000 | @ | @ | at sign |
65 | 41 | 101 | 01000001 | A | A | |
66 | 42 | 102 | 01000010 | B | B | |
67 | 43 | 103 | 01000011 | C | C | |
68 | 44 | 104 | 01000100 | D | D | |
69 | 45 | 105 | 01000101 | E | E | |
70 | 46 | 106 | 01000110 | F | F | |
71 | 47 | 107 | 01000111 | G | G | |
72 | 48 | 110 | 01001000 | H | H | |
73 | 49 | 111 | 01001001 | I | I | |
74 | 4A | 112 | 01001010 | J | J | |
75 | 4B | 113 | 01001011 | K | K | |
76 | 4C | 114 | 01001100 | L | L | |
77 | 4D | 115 | 01001101 | M | M | |
78 | 4E | 116 | 01001110 | N | N | |
79 | 4F | 117 | 01001111 | O | O | |
80 | 50 | 120 | 01010000 | P | P | |
81 | 51 | 121 | 01010001 | Q | Q | |
82 | 52 | 122 | 01010010 | R | R | |
83 | 53 | 123 | 01010011 | S | S | |
84 | 54 | 124 | 01010100 | T | T | |
85 | 55 | 125 | 01010101 | U | U | |
86 | 56 | 126 | 01010110 | V | V | |
87 | 57 | 127 | 01010111 | W | W | |
88 | 58 | 130 | 01011000 | X | X | |
89 | 59 | 131 | 01011001 | Y | Y | |
90 | 5A | 132 | 01011010 | Z | Z | |
91 | 5B | 133 | 01011011 | [ | [ | left square bracket |
92 | 5C | 134 | 01011100 | \ | \ | backslash |
93 | 5D | 135 | 01011101 | ] | ] | right square bracket |
94 | 5E | 136 | 01011110 | ^ | ^ | caret / circumflex |
95 | 5F | 137 | 01011111 | _ | _ | underscore |
96 | 60 | 140 | 01100000 | ` | ` | grave / accent |
97 | 61 | 141 | 01100001 | a | a | |
98 | 62 | 142 | 01100010 | b | b | |
99 | 63 | 143 | 01100011 | c | c | |
100 | 64 | 144 | 01100100 | d | d | |
101 | 65 | 145 | 01100101 | e | e | |
102 | 66 | 146 | 01100110 | f | f | |
103 | 67 | 147 | 01100111 | g | g | |
104 | 68 | 150 | 01101000 | h | h | |
105 | 69 | 151 | 01101001 | i | i | |
106 | 6A | 152 | 01101010 | j | j | |
107 | 6B | 153 | 01101011 | k | k | |
108 | 6C | 154 | 01101100 | l | l | |
109 | 6D | 155 | 01101101 | m | m | |
110 | 6E | 156 | 01101110 | n | n | |
111 | 6F | 157 | 01101111 | o | o | |
112 | 70 | 160 | 01110000 | p | p | |
113 | 71 | 161 | 01110001 | q | q | |
114 | 72 | 162 | 01110010 | r | r | |
115 | 73 | 163 | 01110011 | s | s | |
116 | 74 | 164 | 01110100 | t | t | |
117 | 75 | 165 | 01110101 | u | u | |
118 | 76 | 166 | 01110110 | v | v | |
119 | 77 | 167 | 01110111 | w | w | |
120 | 78 | 170 | 01111000 | x | x | |
121 | 79 | 171 | 01111001 | y | y | |
122 | 7A | 172 | 01111010 | z | z | |
123 | 7B | 173 | 01111011 | { | { | left curly bracket |
124 | 7C | 174 | 01111100 | | | | | vertical bar |
125 | 7D | 175 | 01111101 | } | } | right curly bracket |
126 | 7E | 176 | 01111110 | ~ | ~ | tilde |
127 | 7F | 177 | 01111111 |  | DEL | delete |
Extended ASCII Table
Dec | Hex | Binary | HTML | Char |
---|---|---|---|---|
128 | 80 | 10000000 | - | |
129 | 81 | 10000001 | - | |
130 | 82 | 10000010 | - | |
131 | 83 | 10000011 | - | |
132 | 84 | 10000100 | - | |
133 | 85 | 10000101 | - | |
134 | 86 | 10000110 | - | |
135 | 87 | 10000111 | - | |
136 | 88 | 10001000 | - | |
137 | 89 | 10001001 | - | |
138 | 8A | 10001010 | - | |
139 | 8B | 10001011 | - | |
140 | 8C | 10001100 | - | |
141 | 8D | 10001101 | - | |
142 | 8E | 10001110 | - | |
143 | 8F | 10001111 | - | |
144 | 90 | 10010000 | - | |
145 | 91 | 10010001 | - | |
146 | 92 | 10010010 | - | |
147 | 93 | 10010011 | - | |
148 | 94 | 10010100 | - | |
149 | 95 | 10010101 | - | |
150 | 96 | 10010110 | - | |
151 | 97 | 10010111 | - | |
152 | 98 | 10011000 | - | |
153 | 99 | 10011001 | - | |
154 | 9A | 10011010 | - | |
155 | 9B | 10011011 | - | |
156 | 9C | 10011100 | - | |
157 | 9D | 10011101 | - | |
158 | 9E | 10011110 | - | |
159 | 9F | 10011111 | - | |
160 | A0 | 10100000 |   | |
161 | A1 | 10100001 | ¡ | ¡ |
162 | A2 | 10100010 | ¢ | ¢ |
163 | A3 | 10100011 | £ | £ |
164 | A4 | 10100100 | ¤ | ¤ |
165 | A5 | 10100101 | ¥ | ¥ |
166 | A6 | 10100110 | ¦ | ¦ |
167 | A7 | 10100111 | § | § |
168 | A8 | 10101000 | ¨ | ¨ |
169 | A9 | 10101001 | © | © |
170 | AA | 10101010 | ª | ª |
171 | AB | 10101011 | « | « |
172 | AC | 10101100 | ¬ | ¬ |
173 | AD | 10101101 | ­ | |
174 | AE | 10101110 | ® | ® |
175 | AF | 10101111 | ¯ | ¯ |
176 | B0 | 10110000 | ° | ° |
177 | B1 | 10110001 | ± | ± |
178 | B2 | 10110010 | ² | ² |
179 | B3 | 10110011 | ³ | ³ |
180 | B4 | 10110100 | ´ | ´ |
181 | B5 | 10110101 | µ | µ |
182 | B6 | 10110110 | ¶ | ¶ |
183 | B7 | 10110111 | · | · |
184 | B8 | 10111000 | ¸ | ¸ |
185 | B9 | 10111001 | ¹ | ¹ |
186 | BA | 10111010 | º | º |
187 | BB | 10111011 | » | » |
188 | BC | 10111100 | ¼ | ¼ |
189 | BD | 10111101 | ½ | ½ |
190 | BE | 10111110 | ¾ | ¾ |
191 | BF | 10111111 | ¿ | ¿ |
192 | C0 | 11000000 | À | À |
193 | C1 | 11000001 | Á | Á |
194 | C2 | 11000010 | Â | Â |
195 | C3 | 11000011 | Ã | Ã |
196 | C4 | 11000100 | Ä | Ä |
197 | C5 | 11000101 | Å | Å |
198 | C6 | 11000110 | Æ | Æ |
199 | C7 | 11000111 | Ç | Ç |
200 | C8 | 11001000 | È | È |
201 | C9 | 11001001 | É | É |
202 | CA | 11001010 | Ê | Ê |
203 | CB | 11001011 | Ë | Ë |
204 | CC | 11001100 | Ì | Ì |
205 | CD | 11001101 | Í | Í |
206 | CE | 11001110 | Î | Î |
207 | CF | 11001111 | Ï | Ï |
208 | D0 | 11010000 | Ð | Ð |
209 | D1 | 11010001 | Ñ | Ñ |
210 | D2 | 11010010 | Ò | Ò |
211 | D3 | 11010011 | Ó | Ó |
212 | D4 | 11010100 | Ô | Ô |
213 | D5 | 11010101 | Õ | Õ |
214 | D6 | 11010110 | Ö | Ö |
215 | D7 | 11010111 | × | × |
216 | D8 | 11011000 | Ø | Ø |
217 | D9 | 11011001 | Ù | Ù |
218 | DA | 11011010 | Ú | Ú |
219 | DB | 11011011 | Û | Û |
220 | DC | 11011100 | Ü | Ü |
221 | DD | 11011101 | Ý | Ý |
222 | DE | 11011110 | Þ | Þ |
223 | DF | 11011111 | ß | ß |
224 | E0 | 11100000 | à | à |
225 | E1 | 11100001 | á | á |
226 | E2 | 11100010 | â | â |
227 | E3 | 11100011 | ã | ã |
228 | E4 | 11100100 | ä | ä |
229 | E5 | 11100101 | å | å |
230 | E6 | 11100110 | æ | æ |
231 | E7 | 11100111 | ç | ç |
232 | E8 | 11101000 | è | è |
233 | E9 | 11101001 | é | é |
234 | EA | 11101010 | ê | ê |
235 | EB | 11101011 | ë | ë |
236 | EC | 11101100 | ì | ì |
237 | ED | 11101101 | í | í |
238 | EE | 11101110 | î | î |
239 | EF | 11101111 | ï | ï |
240 | F0 | 11110000 | ð | ð |
241 | F1 | 11110001 | ñ | ñ |
242 | F2 | 11110010 | ò | ò |
243 | F3 | 11110011 | ó | ó |
244 | F4 | 11110100 | ô | ô |
245 | F5 | 11110101 | õ | õ |
246 | F6 | 11110110 | ö | ö |
247 | F7 | 11110111 | ÷ | ÷ |
248 | F8 | 11111000 | ø | ø |
249 | F9 | 11111001 | ù | ù |
250 | FA | 11111010 | ú | ú |
251 | FB | 11111011 | û | û |
252 | FC | 11111100 | ü | ü |
253 | FD | 11111101 | ý | ý |
254 | FE | 11111110 | þ | þ |
255 | FF | 11111111 | ÿ | ÿ |
@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:
compile(string, '', 'eval')
returns the code object that would have been executed had you doneeval(string)
. Note that you cannot use statements in this mode; only a (single) expression is valid. Used for a single expression.compile(string, '', 'exec')
returns the code object that would have been executed had you doneexec(string)
. You can use any number of statements here. Used for an entire module.compile(string, '', 'single')
is like theexec
mode, but it will ignore everything except for the first statement. Note that anif/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. Ifreal
is omitted, it defaults to0
.imag
- imaginary part. Ifimag
is omitted, it defaults to0
.
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 whichname
attribute is to be removedname
- a string which must be the name of the attribute to be removed from theobject
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 fromdir()
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 quotientq
and remainderr
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 iterationstart
(optional) -enumerate()
starts counting from this number. If start is omitted,0
is taken asstart
.
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 expressionglobals
(optional) - a dictionarylocals
(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.
Both
globals
andlocals
parameters are omitted: If both parameters are omitted (as in our earlier examples), theexpression
is executed in the current scope. You can check the available variables and methods using following code:print(eval('dir()')
Passing
globals
parameter;locals
parameter is omitted: Theglobals
andlocals
parameters (dictionaries) are used for global and local variables respectively. If thelocals
dictionary is omitted, it defaults toglobals
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.
- Passing both
globals
andlocals
dictionaries: You can make needed functions and variables available for use by passing thelocals
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 objectglobals
(optional) - a dictionarylocals
(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.
Both
globals
andlocals
parameters are omitted: If both parameters are omitted (as in our earlier examples), the code expected to be executed byexec()
is executed in the current scope. You can check the available variables and methods using the following code:exec('print(dir())')
Passing
globals
parameter;locals
parameter is omitted: Theglobals
andlocals
parameters (dictionaries) are used for global and local variables respectively. If thelocals
dictionary is omitted, it defaults toglobals
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.
- 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})
- Passing both
globals
andlocals
dictionaries: You can make needed functions and variables available for use by passing thelocals
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
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
Dec | Hex | Oct | Binary | HTML | Char | Description |
---|---|---|---|---|---|---|
0 | 00 | 000 | 00000000 | � | NUL | Null |
1 | 01 | 001 | 00000001 |  | SOH | Start of Header |
2 | 02 | 002 | 00000010 |  | STX | Start of Text |
3 | 03 | 003 | 00000011 |  | ETX | End of Text |
4 | 04 | 004 | 00000100 |  | EOT | End of Transmission |
5 | 05 | 005 | 00000101 |  | ENQ | Enquiry |
6 | 06 | 006 | 00000110 |  | ACK | Acknowledge |
7 | 07 | 007 | 00000111 |  | BEL | Bell |
8 | 08 | 010 | 00001000 |  | BS | Backspace |
9 | 09 | 011 | 00001001 | 	 | HT | Horizontal Tab |
10 | 0A | 012 | 00001010 | | LF | Line Feed |
11 | 0B | 013 | 00001011 |  | VT | Vertical Tab |
12 | 0C | 014 | 00001100 |  | FF | Form Feed |
13 | 0D | 015 | 00001101 | | CR | Carriage Return |
14 | 0E | 016 | 00001110 |  | SO | Shift Out |
15 | 0F | 017 | 00001111 |  | SI | Shift In |
16 | 10 | 020 | 00010000 |  | DLE | Data Link Escape |
17 | 11 | 021 | 00010001 |  | DC1 | Device Control 1 |
18 | 12 | 022 | 00010010 |  | DC2 | Device Control 2 |
19 | 13 | 023 | 00010011 |  | DC3 | Device Control 3 |
20 | 14 | 024 | 00010100 |  | DC4 | Device Control 4 |
21 | 15 | 025 | 00010101 |  | NAK | Negative Acknowledge |
22 | 16 | 026 | 00010110 |  | SYN | Synchronize |
23 | 17 | 027 | 00010111 |  | ETB | End of Transmission Block |
24 | 18 | 030 | 00011000 |  | CAN | Cancel |
25 | 19 | 031 | 00011001 |  | EM | End of Medium |
26 | 1A | 032 | 00011010 |  | SUB | Substitute |
27 | 1B | 033 | 00011011 |  | ESC | Escape |
28 | 1C | 034 | 00011100 |  | FS | File Separator |
29 | 1D | 035 | 00011101 |  | GS | Group Separator |
30 | 1E | 036 | 00011110 |  | RS | Record Separator |
31 | 1F | 037 | 00011111 |  | US | Unit Separator |
32 | 20 | 040 | 00100000 |   | space | Space |
33 | 21 | 041 | 00100001 | ! | ! | exclamation mark |
34 | 22 | 042 | 00100010 | " | " | double quote |
35 | 23 | 043 | 00100011 | # | # | number |
36 | 24 | 044 | 00100100 | $ | $ | dollar |
37 | 25 | 045 | 00100101 | % | % | percent |
38 | 26 | 046 | 00100110 | & | & | ampersand |
39 | 27 | 047 | 00100111 | ' | ' | single quote |
40 | 28 | 050 | 00101000 | ( | ( | left parenthesis |
41 | 29 | 051 | 00101001 | ) | ) | right parenthesis |
42 | 2A | 052 | 00101010 | * | * | asterisk |
43 | 2B | 053 | 00101011 | + | + | plus |
44 | 2C | 054 | 00101100 | , | , | comma |
45 | 2D | 055 | 00101101 | - | - | minus |
46 | 2E | 056 | 00101110 | . | . | period |
47 | 2F | 057 | 00101111 | / | / | slash |
48 | 30 | 060 | 00110000 | 0 | 0 | zero |
49 | 31 | 061 | 00110001 | 1 | 1 | one |
50 | 32 | 062 | 00110010 | 2 | 2 | two |
51 | 33 | 063 | 00110011 | 3 | 3 | three |
52 | 34 | 064 | 00110100 | 4 | 4 | four |
53 | 35 | 065 | 00110101 | 5 | 5 | five |
54 | 36 | 066 | 00110110 | 6 | 6 | six |
55 | 37 | 067 | 00110111 | 7 | 7 | seven |
56 | 38 | 070 | 00111000 | 8 | 8 | eight |
57 | 39 | 071 | 00111001 | 9 | 9 | nine |
58 | 3A | 072 | 00111010 | : | : | colon |
59 | 3B | 073 | 00111011 | ; | ; | |
60 | 3C | 074 | 00111100 | < | < | less than |
61 | 3D | 075 | 00111101 | = | = | equality sign |
62 | 3E | 076 | 00111110 | > | > | greater than |
63 | 3F | 077 | 00111111 | ? | ? | question mark |
64 | 40 | 100 | 01000000 | @ | @ | at sign |
65 | 41 | 101 | 01000001 | A | A | |
66 | 42 | 102 | 01000010 | B | B | |
67 | 43 | 103 | 01000011 | C | C | |
68 | 44 | 104 | 01000100 | D | D | |
69 | 45 | 105 | 01000101 | E | E | |
70 | 46 | 106 | 01000110 | F | F | |
71 | 47 | 107 | 01000111 | G | G | |
72 | 48 | 110 | 01001000 | H | H | |
73 | 49 | 111 | 01001001 | I | I | |
74 | 4A | 112 | 01001010 | J | J | |
75 | 4B | 113 | 01001011 | K | K | |
76 | 4C | 114 | 01001100 | L | L | |
77 | 4D | 115 | 01001101 | M | M | |
78 | 4E | 116 | 01001110 | N | N | |
79 | 4F | 117 | 01001111 | O | O | |
80 | 50 | 120 | 01010000 | P | P | |
81 | 51 | 121 | 01010001 | Q | Q | |
82 | 52 | 122 | 01010010 | R | R | |
83 | 53 | 123 | 01010011 | S | S | |
84 | 54 | 124 | 01010100 | T | T | |
85 | 55 | 125 | 01010101 | U | U | |
86 | 56 | 126 | 01010110 | V | V | |
87 | 57 | 127 | 01010111 | W | W | |
88 | 58 | 130 | 01011000 | X | X | |
89 | 59 | 131 | 01011001 | Y | Y | |
90 | 5A | 132 | 01011010 | Z | Z | |
91 | 5B | 133 | 01011011 | [ | [ | left square bracket |
92 | 5C | 134 | 01011100 | \ | \ | backslash |
93 | 5D | 135 | 01011101 | ] | ] | right square bracket |
94 | 5E | 136 | 01011110 | ^ | ^ | caret / circumflex |
95 | 5F | 137 | 01011111 | _ | _ | underscore |
96 | 60 | 140 | 01100000 | ` | ` | grave / accent |
97 | 61 | 141 | 01100001 | a | a | |
98 | 62 | 142 | 01100010 | b | b | |
99 | 63 | 143 | 01100011 | c | c | |
100 | 64 | 144 | 01100100 | d | d | |
101 | 65 | 145 | 01100101 | e | e | |
102 | 66 | 146 | 01100110 | f | f | |
103 | 67 | 147 | 01100111 | g | g | |
104 | 68 | 150 | 01101000 | h | h | |
105 | 69 | 151 | 01101001 | i | i | |
106 | 6A | 152 | 01101010 | j | j | |
107 | 6B | 153 | 01101011 | k | k | |
108 | 6C | 154 | 01101100 | l | l | |
109 | 6D | 155 | 01101101 | m | m | |
110 | 6E | 156 | 01101110 | n | n | |
111 | 6F | 157 | 01101111 | o | o | |
112 | 70 | 160 | 01110000 | p | p | |
113 | 71 | 161 | 01110001 | q | q | |
114 | 72 | 162 | 01110010 | r | r | |
115 | 73 | 163 | 01110011 | s | s | |
116 | 74 | 164 | 01110100 | t | t | |
117 | 75 | 165 | 01110101 | u | u | |
118 | 76 | 166 | 01110110 | v | v | |
119 | 77 | 167 | 01110111 | w | w | |
120 | 78 | 170 | 01111000 | x | x | |
121 | 79 | 171 | 01111001 | y | y | |
122 | 7A | 172 | 01111010 | z | z | |
123 | 7B | 173 | 01111011 | { | { | left curly bracket |
124 | 7C | 174 | 01111100 | | | | | vertical bar |
125 | 7D | 175 | 01111101 | } | } | right curly bracket |
126 | 7E | 176 | 01111110 | ~ | ~ | tilde |
127 | 7F | 177 | 01111111 |  | DEL | delete |
Extended ASCII Table
Dec | Hex | Binary | HTML | Char |
---|---|---|---|---|
128 | 80 | 10000000 | - | |
129 | 81 | 10000001 | - | |
130 | 82 | 10000010 | - | |
131 | 83 | 10000011 | - | |
132 | 84 | 10000100 | - | |
133 | 85 | 10000101 | - | |
134 | 86 | 10000110 | - | |
135 | 87 | 10000111 | - | |
136 | 88 | 10001000 | - | |
137 | 89 | 10001001 | - | |
138 | 8A | 10001010 | - | |
139 | 8B | 10001011 | - | |
140 | 8C | 10001100 | - | |
141 | 8D | 10001101 | - | |
142 | 8E | 10001110 | - | |
143 | 8F | 10001111 | - | |
144 | 90 | 10010000 | - | |
145 | 91 | 10010001 | - | |
146 | 92 | 10010010 | - | |
147 | 93 | 10010011 | - | |
148 | 94 | 10010100 | - | |
149 | 95 | 10010101 | - | |
150 | 96 | 10010110 | - | |
151 | 97 | 10010111 | - | |
152 | 98 | 10011000 | - | |
153 | 99 | 10011001 | - | |
154 | 9A | 10011010 | - | |
155 | 9B | 10011011 | - | |
156 | 9C | 10011100 | - | |
157 | 9D | 10011101 | - | |
158 | 9E | 10011110 | - | |
159 | 9F | 10011111 | - | |
160 | A0 | 10100000 |   | |
161 | A1 | 10100001 | ¡ | ¡ |
162 | A2 | 10100010 | ¢ | ¢ |
163 | A3 | 10100011 | £ | £ |
164 | A4 | 10100100 | ¤ | ¤ |
165 | A5 | 10100101 | ¥ | ¥ |
166 | A6 | 10100110 | ¦ | ¦ |
167 | A7 | 10100111 | § | § |
168 | A8 | 10101000 | ¨ | ¨ |
169 | A9 | 10101001 | © | © |
170 | AA | 10101010 | ª | ª |
171 | AB | 10101011 | « | « |
172 | AC | 10101100 | ¬ | ¬ |
173 | AD | 10101101 | ­ | |
174 | AE | 10101110 | ® | ® |
175 | AF | 10101111 | ¯ | ¯ |
176 | B0 | 10110000 | ° | ° |
177 | B1 | 10110001 | ± | ± |
178 | B2 | 10110010 | ² | ² |
179 | B3 | 10110011 | ³ | ³ |
180 | B4 | 10110100 | ´ | ´ |
181 | B5 | 10110101 | µ | µ |
182 | B6 | 10110110 | ¶ | ¶ |
183 | B7 | 10110111 | · | · |
184 | B8 | 10111000 | ¸ | ¸ |
185 | B9 | 10111001 | ¹ | ¹ |
186 | BA | 10111010 | º | º |
187 | BB | 10111011 | » | » |
188 | BC | 10111100 | ¼ | ¼ |
189 | BD | 10111101 | ½ | ½ |
190 | BE | 10111110 | ¾ | ¾ |
191 | BF | 10111111 | ¿ | ¿ |
192 | C0 | 11000000 | À | À |
193 | C1 | 11000001 | Á | Á |
194 | C2 | 11000010 | Â | Â |
195 | C3 | 11000011 | Ã | Ã |
196 | C4 | 11000100 | Ä | Ä |
197 | C5 | 11000101 | Å | Å |
198 | C6 | 11000110 | Æ | Æ |
199 | C7 | 11000111 | Ç | Ç |
200 | C8 | 11001000 | È | È |
201 | C9 | 11001001 | É | É |
202 | CA | 11001010 | Ê | Ê |
203 | CB | 11001011 | Ë | Ë |
204 | CC | 11001100 | Ì | Ì |
205 | CD | 11001101 | Í | Í |
206 | CE | 11001110 | Î | Î |
207 | CF | 11001111 | Ï | Ï |
208 | D0 | 11010000 | Ð | Ð |
209 | D1 | 11010001 | Ñ | Ñ |
210 | D2 | 11010010 | Ò | Ò |
211 | D3 | 11010011 | Ó | Ó |
212 | D4 | 11010100 | Ô | Ô |
213 | D5 | 11010101 | Õ | Õ |
214 | D6 | 11010110 | Ö | Ö |
215 | D7 | 11010111 | × | × |
216 | D8 | 11011000 | Ø | Ø |
217 | D9 | 11011001 | Ù | Ù |
218 | DA | 11011010 | Ú | Ú |
219 | DB | 11011011 | Û | Û |
220 | DC | 11011100 | Ü | Ü |
221 | DD | 11011101 | Ý | Ý |
222 | DE | 11011110 | Þ | Þ |
223 | DF | 11011111 | ß | ß |
224 | E0 | 11100000 | à | à |
225 | E1 | 11100001 | á | á |
226 | E2 | 11100010 | â | â |
227 | E3 | 11100011 | ã | ã |
228 | E4 | 11100100 | ä | ä |
229 | E5 | 11100101 | å | å |
230 | E6 | 11100110 | æ | æ |
231 | E7 | 11100111 | ç | ç |
232 | E8 | 11101000 | è | è |
233 | E9 | 11101001 | é | é |
234 | EA | 11101010 | ê | ê |
235 | EB | 11101011 | ë | ë |
236 | EC | 11101100 | ì | ì |
237 | ED | 11101101 | í | í |
238 | EE | 11101110 | î | î |
239 | EF | 11101111 | ï | ï |
240 | F0 | 11110000 | ð | ð |
241 | F1 | 11110001 | ñ | ñ |
242 | F2 | 11110010 | ò | ò |
243 | F3 | 11110011 | ó | ó |
244 | F4 | 11110100 | ô | ô |
245 | F5 | 11110101 | õ | õ |
246 | F6 | 11110110 | ö | ö |
247 | F7 | 11110111 | ÷ | ÷ |
248 | F8 | 11111000 | ø | ø |
249 | F9 | 11111001 | ù | ù |
250 | FA | 11111010 | ú | ú |
251 | FB | 11111011 | û | û |
252 | FC | 11111100 | ü | ü |
253 | FD | 11111101 | ý | ý |
254 | FE | 11111110 | þ | þ |
255 | FF | 11111111 | ÿ | ÿ |
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:
Character | Meaning |
---|---|
'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()
returnsTrue
) 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 aValueError
exception if there is an encoding error. The default value ofNone
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 thesurrogateescape
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
isNone
, 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
isNone
, any'\n'
characters written are translated to the system default line separator,os.linesep
. Ifnewline
is''
or'\n'
, no translation takes place. Ifnewline
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 ofOSError
.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:
- Support added to accept objects implementing
os.PathLike
. - On Windows, opening a console buffer may return a subclass of
io.RawIOBase
other thanio.FileIO
.
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
Dec | Hex | Oct | Binary | HTML | Char | Description |
---|---|---|---|---|---|---|
0 | 00 | 000 | 00000000 | � | NUL | Null |
1 | 01 | 001 | 00000001 |  | SOH | Start of Header |
2 | 02 | 002 | 00000010 |  | STX | Start of Text |
3 | 03 | 003 | 00000011 |  | ETX | End of Text |
4 | 04 | 004 | 00000100 |  | EOT | End of Transmission |
5 | 05 | 005 | 00000101 |  | ENQ | Enquiry |
6 | 06 | 006 | 00000110 |  | ACK | Acknowledge |
7 | 07 | 007 | 00000111 |  | BEL | Bell |
8 | 08 | 010 | 00001000 |  | BS | Backspace |
9 | 09 | 011 | 00001001 | 	 | HT | Horizontal Tab |
10 | 0A | 012 | 00001010 | | LF | Line Feed |
11 | 0B | 013 | 00001011 |  | VT | Vertical Tab |
12 | 0C | 014 | 00001100 |  | FF | Form Feed |
13 | 0D | 015 | 00001101 | | CR | Carriage Return |
14 | 0E | 016 | 00001110 |  | SO | Shift Out |
15 | 0F | 017 | 00001111 |  | SI | Shift In |
16 | 10 | 020 | 00010000 |  | DLE | Data Link Escape |
17 | 11 | 021 | 00010001 |  | DC1 | Device Control 1 |
18 | 12 | 022 | 00010010 |  | DC2 | Device Control 2 |
19 | 13 | 023 | 00010011 |  | DC3 | Device Control 3 |
20 | 14 | 024 | 00010100 |  | DC4 | Device Control 4 |
21 | 15 | 025 | 00010101 |  | NAK | Negative Acknowledge |
22 | 16 | 026 | 00010110 |  | SYN | Synchronize |
23 | 17 | 027 | 00010111 |  | ETB | End of Transmission Block |
24 | 18 | 030 | 00011000 |  | CAN | Cancel |
25 | 19 | 031 | 00011001 |  | EM | End of Medium |
26 | 1A | 032 | 00011010 |  | SUB | Substitute |
27 | 1B | 033 | 00011011 |  | ESC | Escape |
28 | 1C | 034 | 00011100 |  | FS | File Separator |
29 | 1D | 035 | 00011101 |  | GS | Group Separator |
30 | 1E | 036 | 00011110 |  | RS | Record Separator |
31 | 1F | 037 | 00011111 |  | US | Unit Separator |
32 | 20 | 040 | 00100000 |   | space | Space |
33 | 21 | 041 | 00100001 | ! | ! | exclamation mark |
34 | 22 | 042 | 00100010 | " | " | double quote |
35 | 23 | 043 | 00100011 | # | # | number |
36 | 24 | 044 | 00100100 | $ | $ | dollar |
37 | 25 | 045 | 00100101 | % | % | percent |
38 | 26 | 046 | 00100110 | & | & | ampersand |
39 | 27 | 047 | 00100111 | ' | ' | single quote |
40 | 28 | 050 | 00101000 | ( | ( | left parenthesis |
41 | 29 | 051 | 00101001 | ) | ) | right parenthesis |
42 | 2A | 052 | 00101010 | * | * | asterisk |
43 | 2B | 053 | 00101011 | + | + | plus |
44 | 2C | 054 | 00101100 | , | , | comma |
45 | 2D | 055 | 00101101 | - | - | minus |
46 | 2E | 056 | 00101110 | . | . | period |
47 | 2F | 057 | 00101111 | / | / | slash |
48 | 30 | 060 | 00110000 | 0 | 0 | zero |
49 | 31 | 061 | 00110001 | 1 | 1 | one |
50 | 32 | 062 | 00110010 | 2 | 2 | two |
51 | 33 | 063 | 00110011 | 3 | 3 | three |
52 | 34 | 064 | 00110100 | 4 | 4 | four |
53 | 35 | 065 | 00110101 | 5 | 5 | five |
54 | 36 | 066 | 00110110 | 6 | 6 | six |
55 | 37 | 067 | 00110111 | 7 | 7 | seven |
56 | 38 | 070 | 00111000 | 8 | 8 | eight |
57 | 39 | 071 | 00111001 | 9 | 9 | nine |
58 | 3A | 072 | 00111010 | : | : | colon |
59 | 3B | 073 | 00111011 | ; | ; | |
60 | 3C | 074 | 00111100 | < | < | less than |
61 | 3D | 075 | 00111101 | = | = | equality sign |
62 | 3E | 076 | 00111110 | > | > | greater than |
63 | 3F | 077 | 00111111 | ? | ? | question mark |
64 | 40 | 100 | 01000000 | @ | @ | at sign |
65 | 41 | 101 | 01000001 | A | A | |
66 | 42 | 102 | 01000010 | B | B | |
67 | 43 | 103 | 01000011 | C | C | |
68 | 44 | 104 | 01000100 | D | D | |
69 | 45 | 105 | 01000101 | E | E | |
70 | 46 | 106 | 01000110 | F | F | |
71 | 47 | 107 | 01000111 | G | G | |
72 | 48 | 110 | 01001000 | H | H | |
73 | 49 | 111 | 01001001 | I | I | |
74 | 4A | 112 | 01001010 | J | J | |
75 | 4B | 113 | 01001011 | K | K | |
76 | 4C | 114 | 01001100 | L | L | |
77 | 4D | 115 | 01001101 | M | M | |
78 | 4E | 116 | 01001110 | N | N | |
79 | 4F | 117 | 01001111 | O | O | |
80 | 50 | 120 | 01010000 | P | P | |
81 | 51 | 121 | 01010001 | Q | Q | |
82 | 52 | 122 | 01010010 | R | R | |
83 | 53 | 123 | 01010011 | S | S | |
84 | 54 | 124 | 01010100 | T | T | |
85 | 55 | 125 | 01010101 | U | U | |
86 | 56 | 126 | 01010110 | V | V | |
87 | 57 | 127 | 01010111 | W | W | |
88 | 58 | 130 | 01011000 | X | X | |
89 | 59 | 131 | 01011001 | Y | Y | |
90 | 5A | 132 | 01011010 | Z | Z | |
91 | 5B | 133 | 01011011 | [ | [ | left square bracket |
92 | 5C | 134 | 01011100 | \ | \ | backslash |
93 | 5D | 135 | 01011101 | ] | ] | right square bracket |
94 | 5E | 136 | 01011110 | ^ | ^ | caret / circumflex |
95 | 5F | 137 | 01011111 | _ | _ | underscore |
96 | 60 | 140 | 01100000 | ` | ` | grave / accent |
97 | 61 | 141 | 01100001 | a | a | |
98 | 62 | 142 | 01100010 | b | b | |
99 | 63 | 143 | 01100011 | c | c | |
100 | 64 | 144 | 01100100 | d | d | |
101 | 65 | 145 | 01100101 | e | e | |
102 | 66 | 146 | 01100110 | f | f | |
103 | 67 | 147 | 01100111 | g | g | |
104 | 68 | 150 | 01101000 | h | h | |
105 | 69 | 151 | 01101001 | i | i | |
106 | 6A | 152 | 01101010 | j | j | |
107 | 6B | 153 | 01101011 | k | k | |
108 | 6C | 154 | 01101100 | l | l | |
109 | 6D | 155 | 01101101 | m | m | |
110 | 6E | 156 | 01101110 | n | n | |
111 | 6F | 157 | 01101111 | o | o | |
112 | 70 | 160 | 01110000 | p | p | |
113 | 71 | 161 | 01110001 | q | q | |
114 | 72 | 162 | 01110010 | r | r | |
115 | 73 | 163 | 01110011 | s | s | |
116 | 74 | 164 | 01110100 | t | t | |
117 | 75 | 165 | 01110101 | u | u | |
118 | 76 | 166 | 01110110 | v | v | |
119 | 77 | 167 | 01110111 | w | w | |
120 | 78 | 170 | 01111000 | x | x | |
121 | 79 | 171 | 01111001 | y | y | |
122 | 7A | 172 | 01111010 | z | z | |
123 | 7B | 173 | 01111011 | { | { | left curly bracket |
124 | 7C | 174 | 01111100 | | | | | vertical bar |
125 | 7D | 175 | 01111101 | } | } | right curly bracket |
126 | 7E | 176 | 01111110 | ~ | ~ | tilde |
127 | 7F | 177 | 01111111 |  | DEL | delete |
Extended ASCII Table
Dec | Hex | Binary | HTML | Char |
---|---|---|---|---|
128 | 80 | 10000000 | - | |
129 | 81 | 10000001 | - | |
130 | 82 | 10000010 | - | |
131 | 83 | 10000011 | - | |
132 | 84 | 10000100 | - | |
133 | 85 | 10000101 | - | |
134 | 86 | 10000110 | - | |
135 | 87 | 10000111 | - | |
136 | 88 | 10001000 | - | |
137 | 89 | 10001001 | - | |
138 | 8A | 10001010 | - | |
139 | 8B | 10001011 | - | |
140 | 8C | 10001100 | - | |
141 | 8D | 10001101 | - | |
142 | 8E | 10001110 | - | |
143 | 8F | 10001111 | - | |
144 | 90 | 10010000 | - | |
145 | 91 | 10010001 | - | |
146 | 92 | 10010010 | - | |
147 | 93 | 10010011 | - | |
148 | 94 | 10010100 | - | |
149 | 95 | 10010101 | - | |
150 | 96 | 10010110 | - | |
151 | 97 | 10010111 | - | |
152 | 98 | 10011000 | - | |
153 | 99 | 10011001 | - | |
154 | 9A | 10011010 | - | |
155 | 9B | 10011011 | - | |
156 | 9C | 10011100 | - | |
157 | 9D | 10011101 | - | |
158 | 9E | 10011110 | - | |
159 | 9F | 10011111 | - | |
160 | A0 | 10100000 |   | |
161 | A1 | 10100001 | ¡ | ¡ |
162 | A2 | 10100010 | ¢ | ¢ |
163 | A3 | 10100011 | £ | £ |
164 | A4 | 10100100 | ¤ | ¤ |
165 | A5 | 10100101 | ¥ | ¥ |
166 | A6 | 10100110 | ¦ | ¦ |
167 | A7 | 10100111 | § | § |
168 | A8 | 10101000 | ¨ | ¨ |
169 | A9 | 10101001 | © | © |
170 | AA | 10101010 | ª | ª |
171 | AB | 10101011 | « | « |
172 | AC | 10101100 | ¬ | ¬ |
173 | AD | 10101101 | ­ | |
174 | AE | 10101110 | ® | ® |
175 | AF | 10101111 | ¯ | ¯ |
176 | B0 | 10110000 | ° | ° |
177 | B1 | 10110001 | ± | ± |
178 | B2 | 10110010 | ² | ² |
179 | B3 | 10110011 | ³ | ³ |
180 | B4 | 10110100 | ´ | ´ |
181 | B5 | 10110101 | µ | µ |
182 | B6 | 10110110 | ¶ | ¶ |
183 | B7 | 10110111 | · | · |
184 | B8 | 10111000 | ¸ | ¸ |
185 | B9 | 10111001 | ¹ | ¹ |
186 | BA | 10111010 | º | º |
187 | BB | 10111011 | » | » |
188 | BC | 10111100 | ¼ | ¼ |
189 | BD | 10111101 | ½ | ½ |
190 | BE | 10111110 | ¾ | ¾ |
191 | BF | 10111111 | ¿ | ¿ |
192 | C0 | 11000000 | À | À |
193 | C1 | 11000001 | Á | Á |
194 | C2 | 1100 |