0% found this document useful (0 votes)
12 views2 pages

Python Methods Reference Guide

The document provides a comprehensive reference for Python's built-in functions and various methods for data types including strings, lists, dictionaries, sets, tuples, and files. Each section lists the available methods and functions for the respective data types. This serves as a quick guide for Python developers to access method functionalities.

Uploaded by

romex55303
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views2 pages

Python Methods Reference Guide

The document provides a comprehensive reference for Python's built-in functions and various methods for data types including strings, lists, dictionaries, sets, tuples, and files. Each section lists the available methods and functions for the respective data types. This serves as a quick guide for Python developers to access method functionalities.

Uploaded by

romex55303
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python Methods and Functions Reference

Built-in Functions
abs(), all(), any(), ascii(), bin(), bool(), bytearray(), bytes()
callable(), chr(), classmethod(), compile(), complex()
delattr(), dict(), dir(), divmod()
enumerate(), eval(), exec()
filter(), float(), format(), frozenset()
getattr(), globals()
hasattr(), hash(), help(), hex()
id(), input(), int(), isinstance(), issubclass(), iter()
len(), list(), locals()
map(), max(), memoryview(), min()
next()
object(), oct(), open(), ord()
pow(), print(), property()
range(), repr(), reversed(), round()
set(), setattr(), slice(), sorted(), staticmethod(), str(), sum(), super()
tuple(), type()
vars(), zip(), __import__()

String Methods (str)


capitalize(), casefold(), center(), count(), encode(), endswith()
expandtabs(), find(), format(), format_map(), index(), isalnum()
isalpha(), isascii(), isdecimal(), isdigit(), isidentifier()
islower(), isnumeric(), isprintable(), isspace(), istitle(), isupper()
join(), ljust(), lower(), lstrip(), maketrans(), partition()
replace(), rfind(), rindex(), rjust(), rpartition(), rsplit()
rstrip(), split(), splitlines(), startswith(), strip()
swapcase(), title(), translate(), upper(), zfill()

List Methods (list)


append(), clear(), copy(), count(), extend(), index()
insert(), pop(), remove(), reverse(), sort()

Dictionary Methods (dict)


clear(), copy(), fromkeys(), get(), items()
keys(), pop(), popitem(), setdefault(), update(), values()

Set Methods (set, frozenset)


add(), clear(), copy(), difference(), difference_update()
discard(), intersection(), intersection_update()
isdisjoint(), issubset(), issuperset()
pop(), remove(), symmetric_difference(), symmetric_difference_update()
union(), update()

Tuple Methods (tuple)


count(), index()

File Methods (file)


close(), detach(), fileno(), flush(), isatty()
read(), readable(), readline(), readlines()
seek(), seekable(), tell(), truncate()
write(), writable(), writelines()

Common questions

Powered by AI

The 'round()' function in Python is used to round a floating-point number to a specified number of decimal places. If the number of places isn't specified, it rounds to the nearest integer. The function uses a round-half-to-even strategy, which can help reduce the bias that might accumulate if numbers are always rounded up or down. However, this approach might lead to unexpected results for those unfamiliar with it, potentially causing issues in financial applications where precision is critical .

'eval()' can be misused in Python by executing malicious code if unvalidated input is evaluated, as it treats the input as a valid Python expression. This can lead to security vulnerabilities if external code execution is possible, such as injection attacks, potentially allowing attackers to manipulate system operations or expose sensitive data. Indiscriminate use of 'eval()' in environments where user input can be executed is risky and should be avoided unless safety measures are in place, like input sanitization or using safer alternatives like 'ast.literal_eval()' .

Using 'with open()' is crucial because it ensures that files are properly closed after their suite finishes, even if an error occurs, which is known as resource management or context management. Explicitly calling 'open()' and 'close()' without using 'with' can lead to resource leaks if the program crashes or an exception is thrown before 'close()' is executed. 'with open()' automatically handles cleanup, reducing the risk of resource leaks and making the code cleaner and more robust .

The 'intersection()' method returns a new set that contains only the elements present in both sets without modifying the original sets. On the other hand, 'intersection_update()' modifies the set on which it is called by removing elements not found in the other specified set(s), effectively keeping only common elements. The main difference is that 'intersection()' does not alter the original sets, while 'intersection_update()' does .

'staticmethod()' in Python is used to define a method that does not interact with class or instance attributes, meaning it does not take the 'self' or 'cls' parameter. It behaves like a regular function belonging to a class's namespace. In contrast, 'classmethod()' receives the class itself, 'cls', as its first argument and is used to define functions that can access and modify class state across all instances. This is particularly useful for factory methods that need to instantiate an object while modifying some class-level attributes .

The 'isupper()' method is useful when checking if all the letters in a string are uppercase, which can be particularly helpful in form validation where specific inputs need to be uppercase. However, this method does not consider numeric or other non-letter characters, which do not affect the return value. Its limitation is that it will return False if the string is empty or if there is at least one lowercase letter, even if most characters are uppercase .

'frozenset' is an immutable version of 'set', meaning its elements cannot be changed or removed after it is created, providing a level of safety when used as dictionary keys or in situations where immutability is required. This immutability also means it lacks methods that modify its contents, such as 'add()' or 'remove()', unlike a 'set', which allows modifications. This attribute makes 'frozenset' ideal for use cases requiring a constant hashable set .

'dir()' returns a list of all the names in the current local scope, including variables, methods, and functions, or in the specified object, excluding methods in the base class. 'globals()', on the other hand, returns a dictionary of the current global symbol table, which holds all information regarding global variables. Both can be helpful in debugging; 'dir()' is used to examine available attributes and methods, while 'globals()' is used to inspect the current state of global variables, helping developers understand what data is available at different points of execution .

The 'map()' function supports functional programming by allowing the application of a given function to all items in an input list (or other iterable) without needing explicit loops, thus making code cleaner and more readable. However, it can become a bottleneck in terms of performance, especially if the function applied is computationally expensive or if the iterable is large because 'map()' processes elements one at a time, potentially leading to higher execution times compared to list comprehensions that can be optimized internally by the Python interpreter .

The 'keys()', 'values()', and 'items()' methods on dictionaries support efficient iteration by providing views that reflect the current state of the dictionary without creating new lists, saving memory and improving performance. 'keys()' returns a dynamic view object of all the keys, 'values()' for values, and 'items()' returns key-value pairs. These views are updated when the dictionary changes, aiding in efficient iteration directly over the dictionary's entries, enhancing performance by avoiding the overhead of duplicating data .

You might also like