Complete Python Functions Cheat Sheet
Complete Python Functions Cheat Sheet
Using 'id()' in Python returns the memory address of an object, thus distinguishing it from others by location in memory rather than value equality. This is useful for identifying unique instances, such as when comparing identity (is the exact object same?), which is critical for avoiding shared state issues in mutable objects. However, using comparison operators like '==' is appropriate for value equality, checking if objects have equivalent content. 'id()' is more appropriate in contexts where object identity impacts logic, such as managing object instances, while '==' focuses on data equivalence .
The 'map()' function in Python applies a given function to all items in an iterable and returns a map object with the results. In contrast, 'filter()' applies a function to an iterable and returns elements for which the function returns True. A 'lambda' function, which creates anonymous functions, can be used with both 'map()' and 'filter()'. For example, list(map(lambda x: x * 2, [1, 2, 3])) uses 'lambda' to double each element in the list . With 'filter()', list(filter(lambda x: x % 2 == 0, [1, 2, 3, 4])) uses 'lambda' to only keep even numbers .
The 'input()' function is used to read data entered by the user, returning it as a string, and is typically used when a program requires user interaction or data entry . For instance, name = input('Enter your name: ') reads a user's input. The 'print()' function, however, displays output on the screen and is used to present information to the user or for debugging purposes, such as print('Hello, World!'). 'input()' is about capturing input, while 'print()' is about displaying output.
The 'range()' function facilitates efficient iteration by generating a sequence of numbers without creating a list in memory, unlike manually defining a list. For example, range(1, 5) generates numbers 1 through 4 directly used in loops. This is more memory-efficient compared to storing a list like [1, 2, 3, 4] when only iterating is needed, as it avoids supplementary data structure operations and reduces memory footprint in extensive iterations, making it ideal for large-scale looping .
The 'pow()' function provides benefits over basic exponentiation (x ** y) by offering an additional modulus parameter, allowing calculations like pow(x, y, z), which computes (x ** y) % z efficiently, especially for large integers where modular arithmetic might be crucial, such as in cryptographic applications. For example, pow(2, 3, 3) computes (2 ** 3) % 3, resulting in 2 . This can significantly reduce computational overhead and enhance performance while providing specific functionality not achievable with simple exponentiation.
The 'len()' function returns the number of items in an object, such as a string, list, or tuple. It's typically used to determine the size or length of these collections. For example, len([1, 2, 3]) returns 3 . In contrast, 'sum()' computes the total sum of the elements in an iterable, which is primarily used with numerical lists. For example, sum([1, 2, 3]) returns 6 . While 'len()' measures size, 'sum()' performs an arithmetic operation on the elements.
In Python, you can use 'zip()' and 'enumerate()' together to iterate over two lists and access both their indices and elements. First, 'zip()' combines the elements from the two lists into tuples. Then, 'enumerate()' adds an index to these tuples. For example, given lists a = [1, 2, 3] and b = ['x', 'y', 'z'], you can use list(enumerate(zip(a, b))) to produce [(0, (1, 'x')), (1, (2, 'y')), (2, (3, 'z'))], which provides both the index and the tuples of elements from a and b .
'isinstance()' should be preferred over 'type()' when checking for type because 'isinstance()' accounts for inheritance, returning True if an object is an instance of a class or its subclasses. This is crucial in object-oriented programming, where polymorphism allows subclasses to be used interchangeally with their parent classes. For example, if class B subclasses A, isinstance(object, A) would return True for an instance of B, while type(object) == A would not, which could lead to less flexible code and potential design issues given an inheritance hierarchy .
The 'abs()' function in Python returns the absolute value of a number, thus converting it to a non-negative form. This is useful in calculations involving distance or magnitude where only size matters, without direction. For example, abs(-10) returns 10 . It complements operations like 'sum()' or 'round()' by ensuring that values are non-negative, which is often crucial in mathematical or financial computations where negative results would be meaningless or require different interpretation.
'sorted()' returns a list sorted in ascending order, while 'reversed()' returns an iterator that processes the list in reverse order. When 'sorted()' and 'reversed()' are combined, such as using list(reversed(sorted([3, 1, 2]))), the result is a list sorted in descending order, [3, 2, 1], because the reverse order is applied to the already sorted ascending list .