Sunday, May 26, 2024

Most Important Things to Know About Python Functions

What is a function in Python?
The most important concept to understand is that in Python, functions are objects. This means a function can return another function and one function can take another function as an argument. We can also define a function within another function. Functions can also be assigned to a variable.
What are some of the built-in functions and methods in Python?
Here’s a list of valuable built-in Python functions and methods that shorten your code and improve its efficiency. Python’s reduce () function iterates over each item in a list, or any other iterable data type, and returns a single value.
Python and Machine Learning Square

Python Built-in Functions and Methods List with Examples

In this article , we will learn about the useful list of Python built-in functions and methods. Let’s understand what Python built-in functions are. Python built-in functions are those functions which are used to solve everyday programming tasks. These built-in functions are based on the functional programming model. We are going to discuss some of the best Python 3 built-in functions and methods in alphabetical order.

I will tell you about mostly used built-in methods in Python 3 along with the real-world examples. Now the question arises why do we need to check out this list, let me tell you why we need to have a look thoroughly in this useful Python 3 built-in functions list because these built-in functions will help us to solve common programming problems daily.

“Ready to take your python skills to the next level? Sign up for a free demo today!”

Built-in functions in Python

Python 3 offers nearly around 68 built-in functions and methods to make python developers life easy. You can see below mostly used Python built-in methods with examples.

Without further ado, Let’s begin checking out this useful Python 2 | 3 built-in methods cheat sheet.

Python has a set of built-in functions.

Function Description
abs() Returns the absolute value of a number
all() Returns True if all items in an iterable object are true
any() Returns True if any item in an iterable object is true
ascii() Returns a readable version of an object. Replaces none-ascii characters with escape character
bin() Returns the binary version of a number
bool() Returns the boolean value of the specified object
bytearray() Returns an array of bytes
bytes() Returns a bytes object
callable() Returns True if the specified object is callable, otherwise False
chr() Returns a character from the specified Unicode code.
classmethod() Converts a method into a class method
compile() Returns the specified source as an object, ready to be executed
complex() Returns a complex number
delattr() Deletes the specified attribute (property or method) from the specified object
dict() Returns a dictionary (Array)
dir() Returns a list of the specified object’s properties and methods
divmod() Returns the quotient and the remainder when argument1 is divided by argument2
enumerate() Takes a collection (e.g. a tuple) and returns it as an enumerate object
eval() Evaluates and executes an expression
exec() Executes the specified code (or object)
filter() Use a filter function to exclude items in an iterable object
float() Returns a floating point number
format() Formats a specified value
frozenset() Returns a frozenset object
getattr() Returns the value of the specified attribute (property or method)
globals() Returns the current global symbol table as a dictionary
hasattr() Returns True if the specified object has the specified attribute (property/method)
hash() Returns the hash value of a specified object
help() Executes the built-in help system
hex() Converts a number into a hexadecimal value
id() Returns the id of an object
input() Allowing user input
int() Returns an integer number
isinstance() Returns True if a specified object is an instance of a specified object
issubclass() Returns True if a specified class is a subclass of a specified object
iter() Returns an iterator object
len() Returns the length of an object
list() Returns a list
locals() Returns an updated dictionary of the current local symbol table
map() Returns the specified iterator with the specified function applied to each item
max() Returns the largest item in an iterable
memoryview() Returns a memory view object
min() Returns the smallest item in an iterable
next() Returns the next item in an iterable
object() Returns a new object
oct() Converts a number into an octal
open() Opens a file and returns a file object
ord() Convert an integer representing the Unicode of the specified character
pow() Returns the value of x to the power of y
print() Prints to the standard output device
property() Gets, sets, deletes a property
range() Returns a sequence of numbers, starting from 0 and increments by 1 (by default)
repr() Returns a readable version of an object
reversed() Returns a reversed iterator
round() Rounds a numbers
set() Returns a new set object
setattr() Sets an attribute (property/method) of an object
slice() Returns a slice object
sorted() Returns a sorted list
staticmethod() Converts a method into a static method
str() Returns a string object
sum() Sums the items of an iterator
super() Returns an object that represents the parent class
tuple() Returns a tuple
type() Returns the type of an object
vars() Returns the __dict__ property of an object
zip() Returns an iterator, from two or more iterators

Python has a set of built-in methods that you can use on strings.

Note: All string methods returns new values. They do not change the original string.

Method Description
capitalize() Converts the first character to upper case
casefold() Converts string into lower case
center() Returns a centered string
count() Returns the number of times a specified value occurs in a string
encode() Returns an encoded version of the string
endswith() Returns true if the string ends with the specified value
expandtabs() Sets the tab size of the string
find() Searches the string for a specified value and returns the position of where it was found
format() Formats specified values in a string
format_map() Formats specified values in a string
index() Searches the string for a specified value and returns the position of where it was found
isalnum() Returns True if all characters in the string are alphanumeric
isalpha() Returns True if all characters in the string are in the alphabet
isascii() Returns True if all characters in the string are ascii characters
isdecimal() Returns True if all characters in the string are decimals
isdigit() Returns True if all characters in the string are digits
isidentifier() Returns True if the string is an identifier
islower() Returns True if all characters in the string are lower case
isnumeric() Returns True if all characters in the string are numeric
isprintable() Returns True if all characters in the string are printable
isspace() Returns True if all characters in the string are whitespaces
istitle() Returns True if the string follows the rules of a title
isupper() Returns True if all characters in the string are upper case
join() Converts the elements of an iterable into a string
ljust() Returns a left justified version of the string
lower() Converts a string into lower case
lstrip() Returns a left trim version of the string
maketrans() Returns a translation table to be used in translations
partition() Returns a tuple where the string is parted into three parts
replace() Returns a string where a specified value is replaced with a specified value
rfind() Searches the string for a specified value and returns the last position of where it was found
rindex() Searches the string for a specified value and returns the last position of where it was found
rjust() Returns a right justified version of the string
rpartition() Returns a tuple where the string is parted into three parts
rsplit() Splits the string at the specified separator, and returns a list
rstrip() Returns a right trim version of the string
split() Splits the string at the specified separator, and returns a list
splitlines() Splits the string at line breaks and returns a list
startswith() Returns true if the string starts with the specified value
strip() Returns a trimmed version of the string
swapcase() Swaps cases, lower case becomes upper case and vice versa
title() Converts the first character of each word to upper case
translate() Returns a translated string
upper() Converts a string into upper case
zfill() Fills the string with a specified number of 0 values at the beginning

Here is the Python built-in functions list.

abs( )
The abs() function in Python get the positive (absolute) value of a numerical value.

x = abs(-7.25)
print(x)
# output = 7.25
all()
The all() function in python checks if all the items of an iterable are true, else it returns False. The all() method also returns true if the iterable object is empty.

list = [0, 2, 2]
a = all(list)
print(a)
# output = False
any()
The any() function returns True if any item in an iterable is true, else it returns False. This method returns False if iterable is empty.

tuple = (0, 1, False)
a = any(tuple)
print(a)
# output = True
ascii()
The ascii() function returns a readable representation of an object (Strings, Tuples, Lists, etc.) It replaces non-ascii characters with escape characters.

a = ascii("Mostly Såne")
print(a)
# output = 'Mostly S\xe5ne'
bin()
The bin() function converts an integer (number) to a binary string. It prefixed with 0b.

a = bin(30)
print(a)
# output = 0b11110
bool()
The bool() function is very helpful in converting an object to a Boolean value. This function returns True, except the object is false, empty, 0 or none.

a = bool(22)
print(a)
# output = True
bytearray()
The bytearray() function is used converts an object into bytearray objects.

a = bytearray(22)
print(a)
# output = bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')
bytes()
The bytes() function is used to convert objects into bytes object.

a = bytes(22)
print(a)
# output: b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'

callable()
The callable() function gets True, and if the passed object is callable, else it returns false.

def a():
  b = 5
print(callable(a))
# output = True
chr()
The chr() function gets the string character, which represents the defined unicode.

a = chr(87)
print(a)
# output: W
compile()
The compile() function compiles the sources into a code.

a = compile('print(45)', 'test', 'eval')
exec(a)
# output: 45
complex()
The complex() function forms a complex number | convert string | number to complex number.

delattr()
The delattr() function help us to remove the defined attribute from the declared object.

class User:
  name = "Jaydon"
  mob = 182182922
  country = "Canada"
delattr(Person, 'age')
dict()
The dict() function form a new dictionary.

a = dict(name = "Jaydon", mob = 182182922, country = "Canada")
print(a)
# output = {'name': 'Jaydon', 'mob': 182182922, 'country': 'Canada'}
dir()
The dir() function gets all the properties and methods of the declared object, and It doesn’t get the values. It even returns the built-in properties which are default for all object.

class User:
  name = "Jaydon"
  mob = 182182922
  country = "Canada"
print(dir(User))
# output = ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'country', 'mob', 'name']
divmod()
Gets a tuple including the quotient and remainder when argument1 is divided by argument2.

a = divmod(6, 2)
print(a)
# output = (3, 0)
enumerate( )
It gets an enumerate object for a sequence or iterator.

a = ('john', 'ann', 'sia')
b = enumerate(a)
print(b)
# output = <enumerate object at 0x7f802a241a20>
eval()
Allows a legal python program to run python code.

a = 'print(28)'
print(eval(a))
exec()
The exec() function executes dynamic python code.

a = 'name = "John"\nprint(name)'
print(exec(a))

filter()
The filter() function filters the sequence via a function, this function checks each elements in the iterator are true or not.
score = [15, 10, 20, 17, 26, 42]
def customFunc(a):
  if a < 20:
    return False
  else:
    return True
players = filter(customFunc, score)
for a in players:
  print(a)
float( )
The float() function transforms a numerical value to floating point.

a = float(5)
print(a)
format()
The format() function transforms the defined value into a specified format.

frozenset()
The frozenset() function gets the unchangeable object.

list = ['Avengers', 'Wonder women', 'Batmen']
a = frozenset(list)
print(a)
getattr()
This function gets the value of the defined attribute from the particular object.

class Student:
  name = "Ann"
  age = 28
  country = "USA"
x = getattr(Student, 'age')
print(x)
# output = 28
globals( )
This function gets the dictionary from the current global symbol table.

a = globals()
print(a)
hasattr()
This function return True, if the defined object has the mentioned attribute, else it will return False.

class Student:
  name = "Ann"
  age = 28
  country = "USA"
x = hasattr(Student, 'age')
print(x)
# output = True
hex()
This method converts the numerical value into a hexadecimal value. The returned value comes with the 0x prefix.

a = hex(225)
print(a)
# output = 0xe1
id()
This method gets a unique id for the defined object, Python provides a unique id to all the objects.

a = ('oppo', 'iPhone', 'nokia')
b = id(a)
print(b)
# output = 140390324530704
input()
A user can define the value using the input() function.

print('What is your name:')
a = input()
print('Hi, ' + a)
# output = Enter your name:
# Digamber
# Hi, Digamber
int()
This function transforms the mentioned value into a numerical value.

a = int(2.9)
print(a)
# output = 2
issubclass()
Returns true, if the defined object is a subclass of the defined object, else it will return false.

class speed:
  kmph = 136
class car(speed):
  name = "BMW"
  speed = speed
x = issubclass(car, speed)
print(x)
iter()
This function gets an iterator object.

x = iter(["john", "lisa", "maria", "ava"])
print(next(x))
print(next(x))
print(next(x))
print(next(x))
# john
# lisa
# maria
# ava
len()
This method returns the total number of elements in an object if an object is a string type, then the method will return the number of characters from the string.

a = ["john", "lisa", "maria", "ava"]
print(len(a))
# 4

list()
The function generates a list object which is ordered and changeable.
a = list(["john", "lisa", "maria", "ava"])
print(len(a))
# 4

Related Posts

Next Post