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
NOTE: Some notes about str
, byte
, bytearray
, and Unicode strings
String Methods
List Methods
Examples from the docs
Dictionary Methods
For several of the entries below, d
refers to the dictionary d
.
Dictionary view objects: The objects returned by dict.keys()
, dict.values()
and dict.items()
are view objects. They provide a dynamic view on the dictionary's entries, which means that when the dictionary changes, the view reflects these changes. Dictionary views can be iterated over to yield their respective data, and support membership tests:
Tuple Methods
See the "Common Sequence Operations" note at the top of this document.
Set Methods
Instances of set
and frozenset
provide the following operations:
issubset(other)
(alternative form: set <= other
)
issuperset(other)
(alternative form: set >= other
)
union(*others)
(alternative form: set | other | ...
)
intersection(*others)
(alternative form: set & other & ...
)
difference(*others)
(alternative form: set - other - ...
)
symmetric_difference(other)
(alternative form: set ^ other
)
The following table lists operations available for set
that do not apply to immutable instances of frozenset
: