Skip to content

Instantly share code, notes, and snippets.

@gto76
Last active July 24, 2023 12:53
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gto76/145776c5eace059b09ca1d6ca771a123 to your computer and use it in GitHub Desktop.
Save gto76/145776c5eace059b09ca1d6ca771a123 to your computer and use it in GitHub Desktop.
Comprehensive Python Cheatsheet up to Datetime, generated by ChatGPT after it was provided with the Dictionary section and grilled about the formatting for some time.

Comprehensive Python Cheatsheet

This version of the Comprehensive Python Cheatsheet was generated by ChatGPT after it was provided with the Dictionary section of the original and grilled about the formatting of the generated String and Set sections with approximately 10 queries. The rest were generated using the '<title>?' query.

List

<list> = []                                   # Creates an empty list.
<list> = [<el>, ...]                          # Creates a list with elements.
<el> = <list>[<index>]                        # Accesses the element at index. Raises IndexError if out of bounds.
<list>[<index>] = <el>                        # Assigns element at index. Raises IndexError if out of bounds.
<list>[<start>:<stop>:<step>]                 # Accesses a range of elements.
del <list>[<index>]                           # Removes the element at index. Raises IndexError if out of bounds.
<list>.append(<el>)                           # Appends an element to the end of the list.
<list>.extend(<iterable>)                     # Appends elements from iterable to the end of the list.
<list>.insert(<index>, <el>)                  # Inserts an element at index.
<list>.remove(<el>)                           # Removes the first occurrence of an element. Raises ValueError if not found.
<list>.pop([<index>])                         # Removes and returns the element at index. If index is omitted, removes and returns the last element.
<list>.clear()                                # Removes all elements.
<list>.index(<el>[, <start>[, <stop>]])       # Returns the first index of an element in the list. Raises ValueError if not found.
<list>.count(<el>)                            # Counts the number of occurrences of an element in the list.
<list>.sort(key=None, reverse=False)          # Sorts the list.
<list>.reverse()                              # Reverses the order of the elements in the list.
<list> = sorted(<iterable>, key=None, reverse=False)  # Returns a new sorted list from the items in iterable.
<list> = list(<iterable>)                     # Creates a new list from an iterable.

Dictionary

<el> in <dict>                                   # Returns True if <el> is a key in <dict>.
<dict>[<el>]                                     # Returns value for <el> in <dict>.
<dict>.get(<el>[, default=None])                 # Returns value for <el> in <dict>. Returns <default> if <el> not found.
<dict>.setdefault(<el>[, default=None])           # Returns value for <el> in <dict>. If <el> not found, writes <default> and returns it.
<dict>.pop(<el>[, default])                       # Removes <el> and returns corresponding value. Raises KeyError if not found, unless <default> is given.
<dict>.popitem()                                  # Removes and returns a (key, value) pair from <dict>. Raises KeyError if dict is empty.
<dict>.keys()                                     # Returns a collection of keys in <dict>. Reflects changes in <dict>.
<dict>.values()                                   # Returns a collection of values in <dict>. Reflects changes in <dict>.
<dict>.items()                                    # Returns a collection of (key, value) tuples in <dict>. Reflects changes in <dict>.
<dict>.update(<dict>)                             # Updates <dict> with key-value pairs from <dict>. Replaces ones with matching keys.
{k: v for k, v in <dict>.items() if k in keys}    # Returns a dictionary, filtered by keys.
{k for k, v in <dict>.items() if v == value}      # Returns set of keys that point to the value.
<dict> = dict(<collection>)                       # Creates a dict from a collection of key-value pairs.
<dict> = dict(zip(keys, values))                  # Creates a dict from two collections.
<dict> = dict.fromkeys(keys [, value])            # Creates a dict with keys from a collection and values set to <value> (default is None).

Set

<set> = set()                            # Creates a new, empty set.
<set> = set(<iterable>)                  # Creates a new set from an iterable.
<set>.add(<el>)                          # Adds an element to the set.
<set>.update(<iterable>)                 # Adds elements from an iterable to the set.
<set>.discard(<el>)                      # Removes an element from the set if it's a member.
<set>.remove(<el>)                       # Removes an element from the set; raises KeyError if not a member.
<el> = <set>.pop()                       # Removes and returns an arbitrary element from the set.
<set>.clear()                            # Removes all elements from the set.
<set> = <set>.copy()                     # Returns a shallow copy of the set.
<set> = <set1> - <set2>                  # Returns the set of elements in set1 but not in set2.
<set> = <set1> | <set2>                  # Returns the set of elements in either set1 or set2.
<set> = <set1> & <set2>                  # Returns the set of elements common to both set1 and set2.
<set> = <set1> ^ <set2>                  # Returns the set of elements in either set1 or set2, but not both.
<bool> = <set1>.isdisjoint(<set2>)       # Returns True if sets have no common elements.
<bool> = <set1>.issubset(<set2>)         # Returns True if all elements of set1 are in set2.
<bool> = <set1>.issuperset(<set2>)       # Returns True if all elements of set2 are in set1.
<el> = <set1>.pop() & <set2>.pop()       # Returns and removes a random element from both sets.

Tuple

<el>   = <tuple>[<int>]               # Accessing an element by index.
<slice> = <tuple>[<start>:<stop>:<step>]  # Slicing tuple by a range.
<bool> = <el> in <tuple>              # Checking if an element is in a tuple.
<int>  = len(<tuple>)                 # Getting the number of elements in a tuple.
<tuple> = <iterable>,                  # Creating a tuple with one element.
<tuple> = (<el1>, <el2>, ..., <elN>)  # Creating a tuple with multiple elements.
<tuple> = <tuple1> + <tuple2>         # Concatenating two tuples.
<tuple> = <tuple> * <int>             # Repeating a tuple by a given number.
<tuple> = tuple(<iterable>)           # Converting an iterable to a tuple.
<int>  = <tuple>.count(<el>)          # Counting occurrences of an element in a tuple.
<int>  = <tuple>.index(<el>)          # Finding the index of the first occurrence of an element.
<el1>, <el2>, ... = <tuple>           # Unpacking a tuple into individual variables.
<tuple> = zip(<iterable1>, <iterable2>, ...)  # Combining iterables into a tuple of tuples.

Range

<range> = range(stop)            # Range from 0 to stop (exclusive) with step 1.
<range> = range(start, stop)     # Range from start to stop (exclusive) with step 1.
<range> = range(start, stop, step)  # Range from start to stop (exclusive) with custom step.
<iter> = iter(<range>)           # Iterator over the range.
<el> in <range>                  # Returns True if el is in the range, False otherwise.
len(<range>)                     # Number of elements in the range.
<range>[index]                   # Returns element at the given index.
<range>[start:stop:step]         # Returns slice of the range.
min(<range>)                     # Smallest element in the range.
max(<range>)                     # Largest element in the range.
sum(<range>)                     # Sum of elements in the range.
<range> == <range>               # Returns True if the ranges are equal, False otherwise.
<range> != <range>               # Returns True if the ranges are not equal, False otherwise.
for <el> in <range>:             # Iterates over the range.
    <statements>

Enumerate

<enumerate> = enumerate(<iterable>, start=0)    # Creates an enumerate object that yields
                                                # pairs of integers and items from iterable.
<iter> = <enumerate>                            # The enumerate object is itself iterable.
<tuple> = next(<enumerate>)                     # Returns the next (index, item) tuple.
<list> = list(<enumerate>)                      # Creates a list of (index, item) tuples.
<str> = str(<enumerate>)                        # Returns a string representation of the object.

Iterator

<iter> = iter(<iterable>)                        # Returns an iterator over the iterable.
<el> = next(<iter>)                             # Returns the next element of the iterator.
<tuple> = itertools.tee(<iter>, n=2)            # Returns n independent iterators from a single one.
<iter> = itertools.chain(<iterable1>, <iterable2>, ...)  # Chains together multiple iterables.
<iter> = itertools.cycle(<iterable>)             # Repeats the iterator indefinitely.
<iter> = itertools.islice(<iterable>, stop)     # Returns the first `stop` elements of the iterator.
<iter> = itertools.islice(<iterable>, start, stop, step=1) # Returns elements from `start` to `stop` by `step`.

Generator

<generator> = (x for x in <iterable>)          # Returns generator that yields from iterable.
<generator> = iter(<function>, sentinel)       # Returns generator that calls function until sentinel.
<generator> = itertools.count(start=0, step=1) # Returns generator that counts indefinitely.
<generator> = itertools.cycle(<iterable>)      # Returns generator that cycles indefinitely over iterable.
<generator> = itertools.repeat(<el>, times)    # Returns generator that repeats element specified number of times.
def <name>(<params>):
    while True:
        yield <val>                             # Yields value, which can be returned to the caller.
<generator> = <name>(<args>)                    # Returns generator from generator function.
<generator>.send(<val>)                         # Sends value to generator as if it was the result of the last yield expression.
<val> = <generator>.throw(<exc>)                # Raises exception of the given type in generator, propagating it until the next yield expression.
<val> = next(<generator>)                       # Advances generator to next yield and returns its value.
<iterable> = iter(<generator>)                  # Returns an iterator from the generator.

Type

type(<obj>)                  # Returns the type of an object.
type(<name>, <bases>, <dict>)# Returns a new type with specified name, bases, and dict.
<result> = isinstance(<obj>, <type>)     # Returns True if obj is an instance of type.
<result> = issubclass(<cls>, <type>)     # Returns True if cls is a subclass of type.

String

<int> = <str>.count(sub[, start[, end]])     # Returns the no. of substr. occurrences.
<str> = <str>.replace(old, new[, count])     # Returns a new str. with old replaced by new.
<str> = <str>.capitalize()                   # Returns a new str. with the first char. capitalized.
<str> = <str>.lower()                        # Returns a new str. with all chars. in lowercase.
<str> = <str>.upper()                        # Returns a new str. with all chars. in uppercase.
<str> = <str>.title()                        # Returns a new str. with the first char. of each word capitalized.
<str> = <str>.strip([chars])                 # Returns a new str. with leading/trailing chars. removed.
<str> = <str>.join(iterable)                 # Returns a new str. which is the concatenation of strings in iterable.
<list> = <str>.split(sep=None, maxsplit=-1)  # Returns a list of substrings separated by sep.

Regex

<match> = re.search(<pattern>, <string>)                 # Searches the first occurrence of a pattern in a string.
<matches> = re.findall(<pattern>, <string>)              # Returns a list of all non-overlapping matches of a pattern in a string.
<matches> = re.finditer(<pattern>, <string>)             # Returns an iterator of all non-overlapping matches of a pattern in a string.
<modified_string> = re.sub(<pattern>, <repl>, <string>)   # Replaces all occurrences of a pattern in a string with a replacement string.
<tokens> = re.split(<pattern>, <string>)                  # Splits a string by occurrences of a pattern and returns a list of tokens.
  • In the above, '<pattern>' is a string that represents the regular expression pattern to be matched, '<string>' is a string that is to be searched for the pattern, and '<repl>' is the replacement string used in the re.sub() method.
  • The re.search() method returns a match object if the pattern is found in the string, otherwise it returns None. The match object contains information about the location of the match in the string.

Format

<str> = format(<el>, <str>)               # Formats the element according to the specified format string.
<str> = '{:<n}'.format(<el>)              # Formats the element in a field n characters wide, left-aligned.
<str> = '{:>n}'.format(<el>)              # Formats the element in a field n characters wide, right-aligned.
<str> = '{:^n}'.format(<el>)              # Formats the element in a field n characters wide, centered.
<str> = '{:n,d}'.format(<el>)             # Formats the element as a decimal number with commas.
<str> = '{:n,e}'.format(<el>)             # Formats the element in scientific notation.
<str> = '{:n,f}'.format(<el>)             # Formats the element as a fixed-point number.
<str> = '{:n,o}'.format(<el>)             # Formats the element as an octal number.
<str> = '{:n,x}'.format(<el>)             # Formats the element as a hexadecimal number (lowercase).
<str> = '{:n,X}'.format(<el>)             # Formats the element as a hexadecimal number (uppercase).
<str> = '{:n,%}'.format(<el>)             # Formats the element as a percentage.
  • In the examples above, '<el>' is the element to be formatted, and '<str>' is the format string. The format function returns a formatted string, while the string format methods return a formatted string as well. The n in the format specification refers to the width of the field, and the d, e, f, o, x, X, and % refer to the various format types available.

Numbers

value = int(<el>)      # Converts an <el> to an integer.
value = float(<el>)    # Converts an <el> to a float.
value = complex(<el>)  # Converts an <el> to a complex number.

Math functions

import math
value = math.sqrt(<float>)       # Returns square root of a float.
value = math.exp(<float>)        # Returns e raised to the power of a float.
value = math.log(<float>[, base])# Returns natural logarithm of a float.
value = math.log10(<float>)      # Returns base-10 logarithm of a float.
value = math.floor(<float>)      # Rounds down a float to the nearest integer.
value = math.ceil(<float>)       # Rounds up a float to the nearest integer.
value = math.trunc(<float>)      # Returns the integer part of a float.
value = math.degrees(<float>)    # Converts a float from radians to degrees.
value = math.radians(<float>)    # Converts a float from degrees to radians.
value = math.sin(<float>)        # Returns the sine of a float (in radians).
value = math.cos(<float>)        # Returns the cosine of a float (in radians).
value = math.tan(<float>)        # Returns the tangent of a float (in radians).
value = math.asin(<float>)       # Returns the arcsine of a float (in radians).
value = math.acos(<float>)       # Returns the arccosine of a float (in radians).
value = math.atan(<float>)       # Returns the arctangent of a float (in radians).
value = math.atan2(<y>, <x>)     # Returns the arctangent of y/x (in radians).

Random numbers

import random
value = random.random()              # Returns a random float between 0 and 1.
value = random.randint(<a>, <b>)     # Returns a random integer between a and b (inclusive).
value = random.uniform(<a>, <b>)     # Returns a random float between a and b.
value = random.choice(<iterable>)    # Returns a random element from an iterable.
value = random.shuffle(<list>)       # Shuffles a list in place.
value = random.sample(<iterable>, k) # Returns k unique random elements from an iterable.

Decimal

from decimal import Decimal
value = Decimal(<el>)            # Constructs a decimal from an <el>.
value = Decimal((<m>, <exp>))    # Constructs a decimal from a tuple (mantissa, exponent).
value = Decimal(str(<el>))       # Constructs a decimal from a string.
value = <dec> + <dec>            # Adds two decimals.
value = <dec> - <dec>            # Subtracts two decimals.
value = <dec> * <dec>            # Multiplies two decimals.
value = <dec> / <dec>            # Divides two decimals.
value = <dec> // <dec>           # Divides and rounds down to the nearest integer.
value = <dec> % <dec>            # Returns the remainder of dividing two decimals.
value = <dec> ** <n>             # Raises a decimal to the power of an integer.
value = <dec>.sqrt()             # Returns the square root of a decimal.
value = <dec>.to_integral_value()# Returns the

Combinatorics

from itertools import permutations, combinations, product, combinations_with_replacement
<iterable> = permutations(<iterable> [, r])  # Generates all possible permutations of length r or len(iterable) if r is None.
<iterable> = combinations(<iterable>, r)      # Generates all possible combinations of length r.
<iterable> = product(<iterable>, repeat=n)    # Generates the Cartesian product of the iterable with itself n times.
<iterable> = combinations_with_replacement(<iterable>, r)  # Generates all possible combinations of length r, allowing repeated elements.
  • Here, '<iterable>' can be any iterable object, and 'r' and 'n' are integers. The result of each function is an iterable object that generates the corresponding combinations or permutations.

Datetime

from datetime import date, datetime, timedelta
<date> = date(year, month, day)           # Date object with the given year, month, and day.
<date> = date.fromisoformat('YYYY-MM-DD') # Date object from the ISO formatted string.
<date> = date.today()                    # Date object representing the current local date.
<date> = date.fromtimestamp(ts)          # Date object from a POSIX timestamp (in seconds).
<datetime> = datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0)
                                         # Datetime object with the given year, month, and day, and optional time.
<datetime> = datetime.fromisoformat('YYYY-MM-DDTHH:MM:SS.ssssss') 
                                         # Datetime object from the ISO formatted string.
<datetime> = datetime.now()              # Datetime object representing the current local date and time.
<datetime> = datetime.utcnow()           # Datetime object representing the current UTC date and time.
<datetime> = datetime.fromtimestamp(ts)  # Datetime object from a POSIX timestamp (in seconds).
<datetime> = datetime.utcfromtimestamp(ts) # Datetime object from a POSIX timestamp (in seconds) in UTC.
<timedelta> = timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
                                         # Time difference object representing a duration.
<datetime> = <datetime> + <timedelta>    # Add a duration to a datetime object.
<datetime> = <datetime> - <timedelta>    # Subtract a duration from a datetime object.
<timedelta> = <datetime> - <datetime>    # Calculate the duration between two datetime objects.
<str> = <datetime>.strftime(format)      # Format a datetime object as a string using the specified format.
<datetime> = datetime.strptime(date_string, format)
                                         # Create a datetime object from a string using the specified format.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment