* **Method iter() is required for `'isinstance(<obj>, abc.Iterable)'` to return True, however any object with getitem() will work with any code expecting an iterable.**
* **Method iter() is required for `'isinstance(<obj>, abc.Iterable)'` to return True, however any object with getitem() will work with any code expecting an iterable.**
* **Abstract base classes that generate missing methods when extended are: Sequence, MutableSequence, Set, MutableSet, Mapping and MutableMapping.**
<div><h2id="list"><ahref="#list"name="list">#</a>List</h2><pre><codeclass="python language-python hljs"><el> = <list>[index] <spanclass="hljs-comment"># First index is 0. Last -1. Allows assignments.</span>
<li><strong>For details about sorted(), min() and max() see <ahref="#sortable">sortable</a>.</strong></li>
<li><strong>For details about sorted(), min() and max() see <ahref="#sortable">sortable</a>.</strong></li>
<li><strong>Module <ahref="#operator">operator</a> provides functions itemgetter() and mul() that offer the same functionality as <ahref="#lambda">lambda</a> expressions above.</strong></li>
<li><strong>Module <ahref="#operator">operator</a> provides functions itemgetter() and mul() that offer the same functionality as <ahref="#lambda">lambda</a> expressions above.</strong></li>
</ul>
</ul>
<pre><codeclass="python language-python hljs"><list>.insert(<int>, <el>) <spanclass="hljs-comment"># Inserts item at index and moves the rest to the right.</span>
<el> = <list>.pop([<int>]) <spanclass="hljs-comment"># Removes and returns item at index or from the end.</span>
<int> = <list>.count(<el>) <spanclass="hljs-comment"># Returns number of occurrences. Also works on strings.</span>
<pre><codeclass="python language-python hljs"><int> = len(<list>) <spanclass="hljs-comment"># Returns number of items. Also works on other collections.</span>
<int> = <list>.count(<el>) <spanclass="hljs-comment"># Returns number of occurrences. Also `if <el> in <coll>: ...`.</span>
<int> = <list>.index(<el>) <spanclass="hljs-comment"># Returns index of the first occurrence or raises ValueError.</span>
<int> = <list>.index(<el>) <spanclass="hljs-comment"># Returns index of the first occurrence or raises ValueError.</span>
<el> = <list>.pop() <spanclass="hljs-comment"># Removes and returns item from the end or at index if passed.</span>
<list>.insert(<int>, <el>) <spanclass="hljs-comment"># Inserts item at index and moves the rest to the right.</span>
<list>.remove(<el>) <spanclass="hljs-comment"># Removes first occurrence of the item or raises ValueError.</span>
<list>.remove(<el>) <spanclass="hljs-comment"># Removes first occurrence of the item or raises ValueError.</span>
<list>.clear() <spanclass="hljs-comment"># Removes all items. Also works on dictionary and set.</span>
<list>.clear() <spanclass="hljs-comment"># Removes all items. Also works on dictionary and set.</span>
<li><strong>When both rounding up and rounding down are possible, the one that returns result with even last digit is chosen. That makes <codeclass="python hljs"><spanclass="hljs-string">'{6.5:.0f}'</span></code> a <codeclass="python hljs"><spanclass="hljs-string">'6'</span></code> and <codeclass="python hljs"><spanclass="hljs-string">'{7.5:.0f}'</span></code> an <codeclass="python hljs"><spanclass="hljs-string">'8'</span></code>.</strong></li>
<li><strong>When both rounding up and rounding down are possible, the one that returns result with even last digit is chosen. That makes <codeclass="python hljs"><spanclass="hljs-string">'{6.5:.0f}'</span></code> a <codeclass="python hljs"><spanclass="hljs-string">'6'</span></code> and <codeclass="python hljs"><spanclass="hljs-string">'{7.5:.0f}'</span></code> an <codeclass="python hljs"><spanclass="hljs-string">'8'</span></code>.</strong></li>
<li><strong>This rule only effects numbers that can be represented exactly by a float (<codeclass="python hljs"><spanclass="hljs-number">.5</span></code>, <codeclass="python hljs"><spanclass="hljs-number">.25</span></code>, …).</strong></li>
<li><strong>This rule only effects numbers that can be represented exactly by a float (<codeclass="python hljs"><spanclass="hljs-number">.5</span></code>, <codeclass="python hljs"><spanclass="hljs-number">.25</span></code>, …).</strong></li>
<div><h3id="ints">Ints</h3><pre><codeclass="python language-python hljs">{<spanclass="hljs-number">90</span>:c} <spanclass="hljs-comment"># 'Z'. Unicode character with value 90.</span>
{<spanclass="hljs-number">90</span>:b} <spanclass="hljs-comment"># '1011010'. Number 90 in binary.</span>
{<spanclass="hljs-number">90</span>:X} <spanclass="hljs-comment"># '5A'. Number 90 in uppercase hexadecimal.</span>
<li><strong>Floats can be compared with: <codeclass="python hljs"><spanclass="hljs-string">'math.isclose(<float>, <float>)'</span></code>.</strong></li>
<li><strong>Floats can be compared with: <codeclass="python hljs"><spanclass="hljs-string">'math.isclose(<float>, <float>)'</span></code>.</strong></li>
<li><strong>Precision of decimal operations is set with: <codeclass="python hljs"><spanclass="hljs-string">'decimal.getcontext().prec = <int>'</span></code>.</strong></li>
<li><strong>Precision of decimal operations is set with: <codeclass="python hljs"><spanclass="hljs-string">'decimal.getcontext().prec = <int>'</span></code>.</strong></li>
<li><strong>Timedelta normalizes arguments to ±days, seconds (< 86 400) and microseconds (< 1M).</strong></li>
<li><strong>Timedelta normalizes arguments to ±days, seconds (< 86 400) and microseconds (< 1M).</strong></li>
<li><strong>Use <codeclass="python hljs"><spanclass="hljs-string">'<D/DT>.weekday()'</span></code> to get the day of the week as an int, with Monday being 0.</strong></li>
<li><strong>Use <codeclass="python hljs"><spanclass="hljs-string">'<D/DT>.weekday()'</span></code> to get the day of the week as an int, with Monday being 0.</strong></li>
</ul>
</ul>
<div><h3id="now">Now</h3><pre><codeclass="python language-python hljs"><D/DTn>= D/DT.today() <spanclass="hljs-comment"># Current local date or naive DT. Also DT.now().</span>
<DTa>= DT.now(<tzinfo>) <spanclass="hljs-comment"># Aware DT from current time in passed timezone.</span>
<div><h3id="now">Now</h3><pre><codeclass="python language-python hljs"><D/DTn> = D/DT.today()<spanclass="hljs-comment"># Current local date or naive DT. Also DT.now().</span>
<DTa> = DT.now(<tzinfo>)<spanclass="hljs-comment"># Aware DT from current time in passed timezone.</span>
</code></pre></div>
</code></pre></div>
<ul>
<ul>
@ -1130,19 +1132,19 @@ Hello World!
<ul>
<ul>
<li><strong>Method iter() is required for <codeclass="python hljs"><spanclass="hljs-string">'isinstance(<obj>, abc.Iterable)'</span></code> to return True, however any object with getitem() will work with any code expecting an iterable.</strong></li>
<li><strong>Method iter() is required for <codeclass="python hljs"><spanclass="hljs-string">'isinstance(<obj>, abc.Iterable)'</span></code> to return True, however any object with getitem() will work with any code expecting an iterable.</strong></li>
<li><strong>Abstract base classes that generate missing methods when extended are: Sequence, MutableSequence, Set, MutableSet, Mapping and MutableMapping.</strong></li>
<li><strong>Names of their required methods are stored in <codeclass="python hljs"><spanclass="hljs-string">'<abc>.__abstractmethods__'</span></code>.</strong></li>
<li><strong>Names of their required methods are stored in <codeclass="python hljs"><spanclass="hljs-string">'<abc>.__abstractmethods__'</span></code>.</strong></li>
</ul>
</ul>
<div><h2id="enum"><ahref="#enum"name="enum">#</a>Enum</h2><pre><codeclass="python language-python hljs"><spanclass="hljs-keyword">from</span> enum <spanclass="hljs-keyword">import</span> Enum, auto
<div><h2id="enum"><ahref="#enum"name="enum">#</a>Enum</h2><p><strong>Class of named constants called members.</strong></p><pre><codeclass="python language-python hljs"><spanclass="hljs-keyword">from</span> enum <spanclass="hljs-keyword">import</span> Enum, auto
<real> = <stat>.st_mtime/st_size/… <spanclass="hljs-comment"># Modification time, size in bytes, ...</span>
<num> = <stat>.st_mtime/st_size/… <spanclass="hljs-comment"># Modification time, size in bytes, ...</span>
</code></pre>
</code></pre>
<div><h3id="direntry">DirEntry</h3><p><strong>Unlike listdir(), scandir() returns DirEntry objects that cache isfile, isdir and on Windows also stat information, thus significantly increasing the performance of code that requires it.</strong></p><pre><codeclass="python language-python hljs"><iter> = os.scandir(path=<spanclass="hljs-string">'.'</span>) <spanclass="hljs-comment"># Returns DirEntry objects located at the path.</span>
<div><h3id="direntry">DirEntry</h3><p><strong>Unlike listdir(), scandir() returns DirEntry objects that cache isfile, isdir and on Windows also stat information, thus significantly increasing the performance of code that requires it.</strong></p><pre><codeclass="python language-python hljs"><iter> = os.scandir(path=<spanclass="hljs-string">'.'</span>) <spanclass="hljs-comment"># Returns DirEntry objects located at the path.</span>
<str> = <DirEntry>.path <spanclass="hljs-comment"># Returns the whole path as a string.</span>
<str> = <DirEntry>.path <spanclass="hljs-comment"># Returns the whole path as a string.</span>
<div><h2id="bytes"><ahref="#bytes"name="bytes">#</a>Bytes</h2><p><strong>Bytes object is an immutable sequence of single bytes. Mutable version is called bytearray.</strong></p><pre><codeclass="python language-python hljs"><bytes> = <spanclass="hljs-string">b'<str>'</span><spanclass="hljs-comment"># Only accepts ASCII characters and \x00-\xff.</span>
<int> = <bytes>[<index>]<spanclass="hljs-comment"># Returns an int in range from 0 to 255.</span>
<div><h2id="bytes"><ahref="#bytes"name="bytes">#</a>Bytes</h2><p><strong>A bytes object is an immutable sequence of single bytes. Mutable version is called bytearray.</strong></p><pre><codeclass="python language-python hljs"><bytes> = <spanclass="hljs-string">b'<str>'</span><spanclass="hljs-comment"># Only accepts ASCII characters and \x00-\xff.</span>
<int> = <bytes>[index] <spanclass="hljs-comment"># Returns an int in range from 0 to 255.</span>
<bytes> = <bytes>[<slice>] <spanclass="hljs-comment"># Returns bytes even if it has only one element.</span>
<bytes> = <bytes>[<slice>] <spanclass="hljs-comment"># Returns bytes even if it has only one element.</span>
<bytes> = <bytes>.join(<coll_of_bytes>) <spanclass="hljs-comment"># Joins elements using bytes as a separator.</span>
<bytes> = <bytes>.join(<coll_of_bytes>) <spanclass="hljs-comment"># Joins elements using bytes as a separator.</span>
</code></pre></div>
</code></pre></div>
<div><h3id="encode-1">Encode</h3><pre><codeclass="python language-python hljs"><bytes> = bytes(<coll_of_ints>) <spanclass="hljs-comment"># Ints must be in range from 0 to 255.</span>
<div><h3id="encode-1">Encode</h3><pre><codeclass="python language-python hljs"><bytes> = bytes(<coll_of_ints>) <spanclass="hljs-comment"># Ints must be in range from 0 to 255.</span>
<bytes> = bytes(<str>, <spanclass="hljs-string">'utf-8'</span>) <spanclass="hljs-comment"># Encodes string. Also <str>.encode('utf-8').</span>
<bytes> = bytes.fromhex(<spanclass="hljs-string">'<hex>'</span>) <spanclass="hljs-comment"># Hex pairs can be separated by whitespaces.</span>
<bytes> = bytes.fromhex(<spanclass="hljs-string">'<hex>'</span>) <spanclass="hljs-comment"># Hex pairs can be separated by whitespaces.</span>
<div><h3id="decode-1">Decode</h3><pre><codeclass="python language-python hljs"><list> = list(<bytes>) <spanclass="hljs-comment"># Returns ints in range from 0 to 255.</span>
<div><h3id="decode-1">Decode</h3><pre><codeclass="python language-python hljs"><list> = list(<bytes>) <spanclass="hljs-comment"># Returns ints in range from 0 to 255.</span>
</ul><div><h4id="besidesnumberspackandunpackalsosupportbytesobjectsaspartofthesequence">Besides numbers, pack() and unpack() also support bytes objects as part of the sequence:</h4><ul>
</ul><div><h4id="besidesnumberspackandunpackalsosupportbytesobjectsasapartofthesequence">Besides numbers, pack() and unpack() also support bytes objects as a part of the sequence:</h4><ul>
<li><strong><codeclass="python hljs"><spanclass="hljs-string">'c'</span></code> - A bytes object with a single element. For pad byte use <codeclass="python hljs"><spanclass="hljs-string">'x'</span></code>.</strong></li>
<li><strong><codeclass="python hljs"><spanclass="hljs-string">'c'</span></code> - A bytes object with a single element. For pad byte use <codeclass="python hljs"><spanclass="hljs-string">'x'</span></code>.</strong></li>
<li><strong><codeclass="apache hljs"><spanclass="hljs-section">'<n>s'</span><spanclass="hljs-attribute"></span></code> - A bytes object with n elements (not effected by byte order).</strong></li>
<li><strong><codeclass="apache hljs"><spanclass="hljs-section">'<n>s'</span><spanclass="hljs-attribute"></span></code> - A bytes object with n elements (not effected by byte order).</strong></li>
</ul></div></div><div><div><h4id="integertypesuseacapitalletterforunsignedtypeminimumandstandardsizesareinbrackets">Integer types. Use a capital letter for unsigned type. Minimum and standard sizes are in brackets:</h4><ul>
</ul></div></div><div><div><h4id="integertypesuseacapitalletterforunsignedtypeminimumandstandardsizesareinbrackets">Integer types. Use a capital letter for unsigned type. Minimum and standard sizes are in brackets:</h4><ul>
<div><h2id="array"><ahref="#array"name="array">#</a>Array</h2><p><strong>List that can only hold numbers of a predefined type. Available types and their minimum sizes in bytes are listed above. Type sizes and byte order are always determined by the system, however bytes of each element can be swapped with byteswap() method.</strong></p><pre><codeclass="python language-python hljs"><spanclass="hljs-keyword">from</span> array <spanclass="hljs-keyword">import</span> array
<div><h2id="array"><ahref="#array"name="array">#</a>Array</h2><p><strong>List that can only hold numbers of a predefined type. Available types and their minimum sizes in bytes are listed above. Type sizes and byte order are always determined by the system, however bytes of each element can be swapped with byteswap() method.</strong></p><pre><codeclass="python language-python hljs"><spanclass="hljs-keyword">from</span> array <spanclass="hljs-keyword">import</span> array
<array> = array(<spanclass="hljs-string">'<typecode>'</span>, <collection>) <spanclass="hljs-comment"># Array from collection of numbers.</span>
<array> = array(<spanclass="hljs-string">'<typecode>'</span>, <coll_of_nums>)<spanclass="hljs-comment"># Array from collection of numbers.</span>
<array> = array(<spanclass="hljs-string">'<typecode>'</span>, <bytes>) <spanclass="hljs-comment"># Array from bytes object.</span>
<array> = array(<spanclass="hljs-string">'<typecode>'</span>, <bytes>) <spanclass="hljs-comment"># Array from bytes object.</span>
<array> = array(<spanclass="hljs-string">'<typecode>'</span>, <array>) <spanclass="hljs-comment"># Treats array as a sequence of numbers.</span>
<array> = array(<spanclass="hljs-string">'<typecode>'</span>, <array>) <spanclass="hljs-comment"># Treats array as a sequence of numbers.</span>
<array>.fromfile(<file>, n_items) <spanclass="hljs-comment"># Appends items. Raises EOFError on end.</span>
<array>.fromfile(<file>, n_items) <spanclass="hljs-comment"># Appends items. Also frombytes().</span>
<real> = <mview>[<index>]<spanclass="hljs-comment"># Returns an int or a float.</span>
<real> = <mview>[index] <spanclass="hljs-comment"># Returns an int or a float.</span>
<mview> = <mview>[<slice>] <spanclass="hljs-comment"># Mview with rearranged elements.</span>
<mview> = <mview>[<slice>] <spanclass="hljs-comment"># Mview with rearranged elements.</span>
<mview> = <mview>.cast(<spanclass="hljs-string">'<typecode>'</span>) <spanclass="hljs-comment"># Casts memoryview to the new format.</span>
<mview> = <mview>.cast(<spanclass="hljs-string">'<typecode>'</span>) <spanclass="hljs-comment"># Casts memoryview to the new format.</span>
<mview>.release() <spanclass="hljs-comment"># Releases memory buffer of target object.</span>
<mview>.release() <spanclass="hljs-comment"># Releases memory buffer of target object.</span>
<array> = array(<spanclass="hljs-string">'<typecode>'</span>, <mview>) <spanclass="hljs-comment"># Treats mview as a sequence of numbers.</span>
<array> = array(<spanclass="hljs-string">'<typecode>'</span>, <mview>) <spanclass="hljs-comment"># Treats mview as a sequence of numbers.</span>
<file>.write(<mview>) <spanclass="hljs-comment"># Writes mview to the binary file.</span>
<file>.write(<mview>) <spanclass="hljs-comment"># Writes mview to the binary file.</span>
</code></pre>
</code></pre>
<pre><codeclass="python language-python hljs"><list>= list(<mview>) <spanclass="hljs-comment"># Returns a list of ints or floats.</span>
<str>= str(<mview>, <spanclass="hljs-string">'utf-8'</span>) <spanclass="hljs-comment"># Treats mview as a bytes object.</span>
<div><h2id="deque"><ahref="#deque"name="deque">#</a>Deque</h2><p><strong>A thread-safe list with efficient appends and pops from either side. Pronounced "deck".</strong></p><pre><codeclass="python language-python hljs"><spanclass="hljs-keyword">from</span> collections <spanclass="hljs-keyword">import</span> deque
<div><h2id="deque"><ahref="#deque"name="deque">#</a>Deque</h2><p><strong>A thread-safe list with efficient appends and pops from either side. Pronounced "deck".</strong></p><pre><codeclass="python language-python hljs"><spanclass="hljs-keyword">from</span> collections <spanclass="hljs-keyword">import</span> deque
<deque> = deque(<collection>) <spanclass="hljs-comment"># Also `maxlen=None`.</span>
<deque> = deque(<collection>) <spanclass="hljs-comment"># Also `maxlen=None`.</span>
@ -2276,7 +2278,7 @@ right = [[<span class="hljs-number">0.1</span>, <span class="hljs-number">0.6</
<Image>.putdata(<list/ImagingCore>) <spanclass="hljs-comment"># Updates pixels with a copy of the sequence.</span>
<Image>.putdata(<list/ImagingCore>) <spanclass="hljs-comment"># Updates pixels with a copy of the sequence.</span>
<Image>.paste(<Image>, (x, y)) <spanclass="hljs-comment"># Draws passed image at specified location.</span>
<Image>.paste(<Image>, (x, y)) <spanclass="hljs-comment"># Draws passed image at specified location.</span>
<pre><codeclass="python language-python hljs"><array> = np.array(<Image>) <spanclass="hljs-comment"># Creates a 2d/3d NumPy array from the image.</span>
<pre><codeclass="python language-python hljs"><array> = np.array(<Image>) <spanclass="hljs-comment"># Creates a 2d/3d NumPy array from the image.</span>
@ -2590,11 +2592,11 @@ Name: a, dtype: int64
<Sr> = pd.Series(<dict/Series>, index=<list>) <spanclass="hljs-comment"># Only keeps items with keys specified in index.</span>
<Sr> = pd.Series(<dict/Series>, index=<list>) <spanclass="hljs-comment"># Only keeps items with keys specified in index.</span>
<pre><codeclass="python language-python hljs"><Sr> = <Sr>><el/Sr><spanclass="hljs-comment"># Returns a Series of bools.</span>
<pre><codeclass="python language-python hljs"><Sr> = <Sr>><el/Sr><spanclass="hljs-comment"># Returns a Series of bools.</span>
@ -2633,7 +2635,7 @@ y <span class="hljs-number">3</span>
</code></pre>
</code></pre>
<ul>
<ul>
<li><strong>Keys/indices/bools can't be tuples because <codeclass="python hljs"><spanclass="hljs-string">'obj[x, y]'</span></code> is converted to <codeclass="python hljs"><spanclass="hljs-string">'obj[(x, y)]'</span></code>!</strong></li>
<li><strong>Indexing objects can't be tuples because <codeclass="python hljs"><spanclass="hljs-string">'obj[x, y]'</span></code> is converted to <codeclass="python hljs"><spanclass="hljs-string">'obj[(x, y)]'</span></code>!</strong></li>
<li><strong>Methods ffill(), interpolate(), fillna() and dropna() accept <codeclass="python hljs"><spanclass="hljs-string">'inplace=True'</span></code>.</strong></li>
<li><strong>Methods ffill(), interpolate(), fillna() and dropna() accept <codeclass="python hljs"><spanclass="hljs-string">'inplace=True'</span></code>.</strong></li>
<li><strong>Last result has a hierarchical index. Use <codeclass="python hljs"><spanclass="hljs-string">'<Sr>[key_1, key_2]'</span></code> to get its values.</strong></li>
<li><strong>Last result has a hierarchical index. Use <codeclass="python hljs"><spanclass="hljs-string">'<Sr>[key_1, key_2]'</span></code> to get its values.</strong></li>
<DF> = pd.read_pickle/excel(<spanclass="hljs-string">'<path/url>'</span>) <spanclass="hljs-comment"># Use `sheet_name=None` to get all Excel sheets.</span>
<DF> = pd.read_pickle/excel(<spanclass="hljs-string">'<path/url>'</span>) <spanclass="hljs-comment"># Use `sheet_name=None` to get all Excel sheets.</span>
<DF> = pd.read_sql(<spanclass="hljs-string">'<table/query>'</span>, <conn.>) <spanclass="hljs-comment"># SQLite3/SQLAlchemy connection (see #SQLite).</span>
<DF> = pd.read_sql(<spanclass="hljs-string">'<table/query>'</span>, <conn.>) <spanclass="hljs-comment"># SQLite3/SQLAlchemy connection (see #SQLite).</span>
</code></pre>
</code></pre>
<pre><codeclass="python language-python hljs"><dict> = <DF>.to_dict([<spanclass="hljs-string">'d/l/s/…'</span>]) <spanclass="hljs-comment"># Returns columns as dicts, lists or series.</span>
<str> = <DF>.to_json/html/csv([<path>])<spanclass="hljs-comment"># Also to_markdown/latex([<path>]).</span>
<pre><codeclass="python language-python hljs"><dict> = <DF>.to_dict(<spanclass="hljs-string">'d/l/s/…'</span>)<spanclass="hljs-comment"># Returns columns as dicts, lists or series.</span>
<str> = <DF>.to_json/html/csv/latex() <spanclass="hljs-comment"># Saves output to file if path is passed.</span>
<DF>.to_pickle/excel(<path>) <spanclass="hljs-comment"># Run `$ pip3 install "pandas[excel]" odfpy`.</span>
<DF>.to_pickle/excel(<path>) <spanclass="hljs-comment"># Run `$ pip3 install "pandas[excel]" odfpy`.</span>
<DF>.to_sql(<spanclass="hljs-string">'<table_name>'</span>, <connection>) <spanclass="hljs-comment"># Also `if_exists='fail/replace/append'`.</span>
<DF>.to_sql(<spanclass="hljs-string">'<table_name>'</span>, <connection>) <spanclass="hljs-comment"># Also `if_exists='fail/replace/append'`.</span>