HomepythonPopular Built-in Functions in Python

Popular Built-in Functions in Python

Python is a high-level, interpreted programming language that comes with a comprehensive standard library. One of the key components of this library is its collection of built-in functions. These functions are pre-defined by the language and can be used directly without any need for additional modules or imports. This article will provide an in-depth look at various categories of Python’s built-in functions, complete with examples and detailed explanations.

Input and Output Functions

print()

The print() function outputs data to the console. It can handle multiple arguments and allows formatting.

print("Hello, World!")  # Outputs: Hello, World!
print("Hello", "World", sep=", ")  # Outputs: Hello, World
  • sep: Specifies the separator between multiple arguments (default is a space).
  • end: Specifies what to print at the end (default is a newline).
input()

The input() function reads a line of input from the user and returns it as a string.

name = input("Enter your name: ")
print("Hello, " + name)
  • Prompts the user with the specified string and waits for input.

Type Conversion Functions

int()

Converts a value to an integer. If the value is a string, it must be a valid integer representation.

num = int("10")  # Converts string to integer
print(num)  # Outputs: 10
  • Raises ValueError if the string does not contain a valid integer.
float()

Converts a value to a floating-point number.

num = float("10.5")  # Converts string to float
print(num)  # Outputs: 10.5
  • Raises ValueError if the string does not contain a valid float.
str()

Converts a value to a string.

text = str(100)  # Converts integer to string
print(text)  # Outputs: "100"
  • Useful for concatenating numbers with strings.

Mathematical Functions

abs()

Returns the absolute value of a number.

absolute_value = abs(-5)  # Outputs: 5
  • Works with both integers and floating-point numbers.
max()

Returns the largest item in an iterable or the largest of two or more arguments.

maximum = max(1, 2, 3)  # Outputs: 3
  • Can take multiple arguments or a single iterable.
min()

Returns the smallest item in an iterable or the smallest of two or more arguments.

minimum = min(1, 2, 3)  # Outputs: 1
  • Can take multiple arguments or a single iterable.
sum()

Sums the items of an iterable, starting from a specified start value (default is 0).

total = sum([1, 2, 3, 4])  # Outputs: 10
  • Accepts an optional start parameter to specify the starting value.
round()

Returns a number rounded to the nearest integer or to a specified number of decimal places.

rounded_number = round(3.14159, 2)  # Outputs: 3.14
  • The second argument specifies the number of decimal places.

Sequence and Collection Functions

len()

Returns the number of items in an object, such as a list, string, or tuple.

length = len("Hello")  # Outputs: 5
  • Works with any object that has a length.
sorted()

Returns a new sorted list from the items in an iterable.

sorted_list = sorted([3, 1, 2])  # Outputs: [1, 2, 3]
  • Accepts optional parameters for specifying a custom sort order and a key function.
reversed()

Returns a reversed iterator over the items in a sequence.

reversed_list = list(reversed([1, 2, 3]))  # Outputs: [3, 2, 1]
  • Works with lists, tuples, and strings.

Utility Functions

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)  # Outputs: 0 a, 1 b, 2 c
  • Useful for accessing both the index and the value in a loop.
zip()

Aggregates elements from two or more iterables, returning an iterator of tuples.

list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
zipped = list(zip(list1, list2))  # Outputs: [(1, 'a'), (2, 'b'), (3, 'c')]
  • Stops when the shortest input iterable is exhausted.
map()

Applies a function to all items in an iterable and returns a map object (an iterator).

def square(x):
    return x * x

squares = list(map(square, [1, 2, 3]))  # Outputs: [1, 4, 9]
  • The first argument is the function, and the second is the iterable.
filter()

Constructs an iterator from elements of an iterable for which a function returns true.

def is_even(x):
    return x % 2 == 0

evens = list(filter(is_even, [1, 2, 3, 4]))  # Outputs: [2, 4]
  • The first argument is the function, and the second is the iterable.

Object and Class Functions

type()

Returns the type of an object.

t = type(123)  # Outputs: <class 'int'>
  • Useful for checking the type of a variable.
isinstance()

Checks if an object is an instance of a class or a tuple of classes.

check = isinstance(123, int)  # Outputs: True
  • The first argument is the object, and the second is the class or tuple of classes.
dir()

Attempts to return a list of valid attributes for an object.

attributes = dir(str)  # Outputs a list of string methods and attributes
  • If no argument is provided, it returns the list of names in the current local scope.

Advanced Utility Functions

eval()

Evaluates a given expression string and returns the result.

result = eval("2 + 2")  # Outputs: 4
  • Be cautious with eval() as it can execute arbitrary code, posing security risks.
exec()

Executes the given source in the context of globals and locals.

code = 'print("Hello, World!")'
exec(code)  # Outputs: Hello, World!
  • Like eval(), be cautious with exec() due to potential security risks.
globals() and locals()

Return the current global and local symbol tables as dictionaries.

global_vars = globals()
local_vars = locals()
  • Useful for debugging and introspection.

Conclusion

Built-in functions are a cornerstone of Python programming, offering optimized, ready-to-use solutions for a wide array of tasks. They enhance efficiency, consistency, and readability, allowing developers to focus on solving complex problems rather than reinventing the wheel.

Subscribe
Notify of

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments

Popular