Skip to main content

Built-in Functions

Python provides a rich set of built-in functions that are always available for use. These functions are part of the Python Standard Library and perform a variety of tasks, such as data type conversion, mathematical operations, input/output operations, and more. Here is an overview of some of the most commonly used built-in functions in Python:

Common Built-in Functions

Data Type Conversion Functions

int(): Converts a value to an integer.

num = int("10")  # Output: 10

float(): Converts a value to a floating-point number.

num = float("10.5") # Output: 10.5

str(): Converts a value to a string.

text = str(10) # Output: '10'

bool(): Converts a value to a boolean.

flag = bool(1) # Output: True

list(): Converts an iterable (e.g., tuple, string) to a list.

my_list = list("hello") # Output: ['h', 'e', 'l', 'l', 'o']

tuple(): Converts an iterable to a tuple.

my_tuple = tuple([1, 2, 3]) # Output: (1, 2, 3)

dict(): Creates a dictionary.

my_dict = dict([('a', 1), ('b', 2)])  # Output: {'a': 1, 'b': 2}

Mathematical Functions

abs(): Returns the absolute value of a number.

result = abs(-5)  # Output: 5
print(result)

round(): Rounds a number to a specified number of decimal places.

result = round(5.678, 2) # Output: 5.68

max(): Returns the largest item in an iterable or the largest of two or more arguments.

result = max(1, 2, 3) # Output: 3

min(): Returns the smallest item in an iterable or the smallest of two or more arguments.

result = min(1, 2, 3) # Output: 1

sum(): Sums the items of an iterable.

result = sum([1, 2, 3]) # Output: 6


Sequence Functions

len(): Returns the length of an object.

result = len("hello")  # Output: 5

range(): Generates a sequence of numbers.

numbers = list(range(1, 5)) # Output: [1, 2, 3, 4]

enumerate(): Adds a counter to an iterable and returns it as an enumerate object.

for index, value in enumerate(['a', 'b', 'c']): print(index, value) # Output: # 0 a # 1 b # 2 c

zip(): Aggregates elements from two or more iterables.

names = ['Alice', 'Bob'] scores = [85, 90] combined = list(zip(names, scores)) # Output: [('Alice', 85), ('Bob', 90)]


Input/Output Functions

print(): Prints the specified message to the console or other standard output device.

print("Hello, world!")  # Output: Hello, world!


input(): Reads a line from input, converts it to a string.

name = input("Enter your name: ") print(f"Hello, {name}!")


Object and Class Functions

type(): Returns the type of an object

result = type(123) # Output: <class 'int'>

isinstance(): Checks if an object is an instance of a class or a tuple of classes.

result = isinstance(123, int) # Output: True

dir(): Returns a list of the specified object's attributes and methods.

attributes = dir([]) # Output: ['__add__', '__class__', ..., 'append', 'clear', ...]

id(): Returns the identity of an object.

obj = "hello" obj_id = id(obj) # Output: 140248162356656 (the actual number will vary)


Other Useful Functions

open(): Opens a file and returns a file object.

file = open("example.txt", "r")
content = file.read()
file.close()

sorted(): Returns a new sorted list from the elements of any iterable.

numbers = [3, 1, 4, 1, 5] sorted_numbers = sorted(numbers) # Output: [1, 1, 3, 4, 5]

reversed(): Returns a reverse iterator.

reversed_list = list(reversed([1, 2, 3])) # Output: [3, 2, 1]


any(): Returns True if any element of the iterable is true.

result = any([0, 1, 2]) # Output: True

all(): Returns True if all elements of the iterable are true.

result = all([1, 2, 3]) # Output: True

eval(): Evaluates a Python expression from a string-based input.

result = eval("2 + 2") # Output: 4

exec(): Executes a dynamic Python code block.

code = "for i in range(3): print(i)" exec(code) # Output: # 0 # 1 # 2

Python's built-in functions provide a powerful toolkit for performing a wide range of tasks efficiently. Familiarity with these functions can greatly enhance your ability to write concise and readable Python code. For a full list of Python's built-in functions, you can refer to the official Python documentation.

Comments

Popular posts from this blog

Performance Optimization

Performance optimization in SQL is crucial for ensuring that your database queries run efficiently, especially as the size and complexity of your data grow. Here are several strategies and techniques to optimize SQL performance: Indexing Create Indexes : Primary Key and Unique Indexes : These are automatically indexed. Ensure that your tables have primary keys and unique constraints where applicable. Foreign Keys : Index foreign key columns to speed up join operations. Composite Indexes : Use these when queries filter on multiple columns. The order of columns in the index should match the order in the query conditions. Avoid Over-Indexing:  Too many indexes can slow down write operations (INSERT, UPDATE, DELETE). Only index columns that are frequently used in WHERE clauses, JOIN conditions, and as sorting keys. Query Optimization Use SELECT Statements Efficiently : SELECT Only Necessary Columns : Avoid using SELECT * ; specify only ...

DAX UPPER Function

The DAX UPPER function in Power BI is used to convert all characters in a text string to uppercase. This function is useful for standardizing text data, ensuring consistency in text values, and performing case-insensitive comparisons. Syntax: UPPER(<text>) <text>: The text string that you want to convert to uppercase. Purpose: The UPPER function helps ensure that text data is consistently formatted in uppercase. This can be essential for tasks like data cleaning, preparing text for comparisons, and ensuring uniformity in text-based fields. E xample: Suppose you have a table named "Customers" with a column "Name" that contains names in mixed case. You want to create a new column that shows all names in uppercase. UppercaseName = UPPER(Customers[Name]) Example Scenario: Assume you have the following "Customers" table: You can use the UPPER function as follows: Using the UPPER function, you can convert all names to uppercase: UppercaseName = ...

TechUplift: Elevating Your Expertise in Every Click

  Unlock the potential of data with SQL Fundamental: Master querying, managing, and manipulating databases effortlessly. Empower your database mastery with PL/SQL: Unleash the full potential of Oracle databases through advanced programming and optimization. Unlock the Potential of Programming for Innovation and Efficiency.  Transform raw data into actionable insights effortlessly. Empower Your Data Strategy with Power Dataware: Unleash the Potential of Data for Strategic Insights and Decision Making.