Python Built-in Functions

Tutorial Playlist

Built-in functions in Python are simple functions that are useful for completing common tasks in just one line of code rather than writing additional code. They are useful for manipulating numbers, strings, lists, and other data types in one line of code to make coding quicker and efficient. Additionally, it provides an opportunity for developers to write cleaner and more readable code without repeatedly writing the same logic. In this blog, you will explore the Python built-in functions, their types, how they are used, and why they are important for writing clean and efficient code in detail, with examples for each.

Table of Contents:

What are Built-in Functions in Python?

Python built-in functions are pre-defined functions that allow everyday tasks to be performed with just a single line of code. These functions are very helpful in handling operations such as working with different types of data, and many more. They are also helpful in writing the Python code cleanly and efficiently without any logic being repeated. This is very important in improving the readability of the code while reducing the chances of getting errors. The Built-in functions are crucial for saving time while performing common operations like finding the length of the list, converting the data types, and other operations. Built-in functions, such as print(), len(), and sum(), can help us manipulate our data, perform calculations, and handle the input/output in Python.

Advantages of Using Built-in Functions in Python

Saves Time and Effort: The built-in functions are capable of completing tasks in one line of code, which saves time by removing extra logic and, of course, extra lines of code.
⦁ Increased Code Readability: The built-in functions are easier to read than writing a whole code to perform an operation, which can be done with a single line of code.
⦁ Less Chance for Errors: The built-in functions have fewer chances of error because the functions are tested and optimised.
⦁ Increased Performance: The built-in functions are more efficient in completing the code execution because they are all optimised for performance.
⦁ Reduced Size of Code: Built-in functions eliminate the need to write lengthy code for common operations, since the point is to make the Python code as concise and simple as possible.
⦁ Enhances Maintainability: Using the built-in functions helps in keeping the code clean and simple, which makes it easier for maintenance and updates that are given in the future.

Unleash the Power of Python – From Coding to Career Growth!
Enroll now and take your Python skills to the next level.
quiz-icon

Key Built-in Functions in Python

1. print()

The print() function is one of the most commonly used built-in functions in Python. It displays program information or results on the screen, which is very valuable for assessing the output of the Python code.

Example:

Python

Output:

print() output

Explanation: Here, the print() function displays the greeting message to the users.

2. len()

The len() is used to return the count of the items that are available in an object. The object can be a string, list, or tuple. This method is very helpful for counting the number of elements.

Example:

Python

Output:

len() output

Explanation: Here, len(courses) returns the total length of the list.

3. type()

The type() function in Python returns the type of an object that has been defined. This is very helpful in an instance where it needs to check the data type that an object represents. The datatype could be a string, an integer, or a list, which ensures that the correct expected type of data is being used.

Example:

Python

Output:

type() output

Explanation: Here, the type(course) helps in retrieving the type of variable and confirms that it is a string.

4. str()

The str() function is used to convert other data types into a string. It is mainly used to format values into a string, which helps improve readability.

Example:

Python

Output:

str() output

Explanation: Here, str(duration) helps in converting the integer 6 into a string, which forms a complete sentence.

5. input()

The input() function allows the user to enter the data requested. This supports the information-gathering process of building interactive programs, in which the programmer can ask users for information during the execution of the code.

Example:

Python

Output:

input() output

Explanation: Here, the input() function is used to ask the user which subject they like the most. The input given by the user is stored in the subject variable. The print() statement prints the statement with the subject name.

6. range()

The range() function generates a sequence of numbers, which is mostly used with loops, that will repeat the function or loop through a sequence.

Example:

Python

Output:

range() output

Explanation: Here, range(5) helps print numbers that are less than 5.

7. sum()

The sum() function is a combination of an iterable or collection, taking all the items in the iterable and adding them together. This is helpful for quick calculations. It adds all items in an iterable from left to right and returns the total.

Example:

Python

Output:

sum() output

Explanation: Here, sum(scores) calculates the total sum of the scores.

8. max()

The max() function helps in returning the largest item in an iterable. It accepts multiple arguments or a single iterable It is useful for identifying the element with the highest value in the list, which is very helpful in data analysis.

Example:

Python

Output:

max() output

Explanation: Here, max(numbers) helps in finding the largest number in the list here which is 30.

9. min()

The min() function returns the smallest item in an iterable. It accepts multiple arguments or a single iterable. It helps to find the lowest value in a dataset or list, which can be important for analysis.

Example:

Python

Output:

min() output

Explanation: Here, min(numbers) returns the smallest number in the list.

10. sorted()

The sorted() function helps in arranging the numbers in an iterable, in ascending or descending order. It is useful in efficiently sorting the data in a particular order for data analysis.

Example:

Python

Output:

sorted() output

Explanation: Here, sorted(values) helps in sorting the list in ascending order.

11. all()

The all() function in Python is used to check whether all the elements in an iterable are true. It is very helpful in checking the condition given by the user. If even one condition is not matched, it will return false.

Example:

Python

Output:

all() output

Explanation: Here, the all() function checks whether all the conditions are true, and false is returned as a false condition exists.

12. any()

The any() function checks if any item in an iterable is true. It is useful for determining that at least one condition is True, such as checking users’ inputs.

Example:

Python

Output:

any() output Explanation: Here, the any() function returns True since at least one element is true.

13. dict()

The dict() function creates a dictionary that is a collection of key-value pairs. The data is organised in pairs, such as the name and the corresponding attribute.

Example:

Python

Output:

dict() output

Explanation: Here, dict() creates a dictionary with student information.

14. list()

The list() function converts an iterable into a list. It is used for transforming the data from any data type to a list-like tuple, into a list for easier manipulation.

Example:

Python

Output:

list() output

Explanation: Here, list(numbers_tuple) converts a tuple into a list.

15. zip()

The zip() function combines two or more iterables into tuples. It is useful as it helps in pairing the related data, such as matching names with ages or combining with another dataset. It returns pairs (or groups) of items from each iterable, matching them by position, and stops when the shortest one runs out.

Example:

Python

Output:

zip() output

Explanation: Here, zip(course_names, durations) displays the name of the course with its corresponding duration.

Get 100% Hike!

Master Most in Demand Skills Now!

Other Common Python Built-in Functions

 

Python Function Description Example
ascii() Returns a printable representation of an object. ascii(‘ä’) → ‘xe4’
bin() Converts an integer to a binary string. bin(5) → ‘0b101’
bool() Converts a value to Boolean. bool(1) → True
bytearray() Returns an array of the given byte size. bytearray(5) → bytearray(b’x00x00x00x00x00′)
bytes() Returns an immutable bytes object. bytes(5) → b’x00x00x00x00x00′
callable() Checks if the object is callable. callable(len) → True
compile() Compiles source into a code object. compile(‘5 + 5’, ‘<string>’, ‘eval’)
complex() Creates a complex number. complex(1, 2) → (1+2j)
delattr() Deletes an attribute from an object. delattr(obj, ‘attr’)
dict() Creates a Python dictionary. dict(a=1, b=2) → {‘a’: 1, ‘b’: 2}
dir() Returns attributes of an object. dir([]) → [‘append’, ‘clear’, …]
enumerate() Returns an enumerate object. enumerate([‘a’, ‘b’]) → (0, ‘a’), (1, ‘b’)
eval() Executes a given string as Python code. eval(‘5 + 5’) → 10
exec() Executes dynamically created Python code. exec(‘a = 5’)
filter() Constructs an iterator from the true elements of an iterable. filter(lambda x: x > 0, [-1, 2]) → [2]
format() Formats a value into a string. ‘{:.2f}’.format(3.14159) → ‘3.14’
frozenset() Returns an immutable frozenset object. frozenset([1, 2]) → frozenset({1, 2})
getattr() Gets the value of a named attribute. getattr(obj, ‘attr’)
globals() Returns the global symbol table as a dictionary. globals() → {‘__name__’: ‘__main__’, …}
hasattr() Checks if an object has a given attribute. hasattr(obj, ‘attr’) → True
hash() Returns the hash value of an object. hash(‘hello’) → 99162322
help() Invokes the built-in help system. help(str)
hex() Converts an integer to a hexadecimal string. hex(255) → ‘0xff’
id() Returns the identity of an object. id(5) → 9783552
isinstance() Checks if an object is an instance of a class. isinstance(5, int) → True
issubclass() Checks if a class is a subclass of another. issubclass(bool, int) → True
iter() Returns an iterator for an object. iter([1, 2, 3])
len() Returns the length of an object. len([1, 2, 3]) → 3
locals() Returns the local symbol table as a dictionary. locals() → {…}
map() Applies a function to an iterable. list(map(str, [1, 2])) → [‘1’, ‘2’]
memoryview() Returns a memory view object. memoryview(b’abc’)
next() Returns the next item from an iterator. next(iter([1, 2])) → 1
object() Creates a featureless object. object()
oct() Converts an integer to octal. oct(8) → ‘0o10’
open() Opens a file and returns a file object. open(‘file.txt’)
ord() Returns the Unicode code point for a character. ord(‘A’) → 65
pow() Returns the power of a number. pow(2, 3) → 8
print() Prints a value to the console. print(‘Hello’)
property() Returns a property object. @property def name(self): return self._name
range() Creates a sequence of integers. range(5) → 0, 1, 2, 3, 4
repr() Returns a string representation of an object. repr(‘test’) → “‘test'”
reversed() Returns a reversed iterator. list(reversed([1, 2])) → [2, 1]
set() Creates a set. set([1, 2, 3])
setattr() Sets the value of an object’s attribute. setattr(obj, ‘attr’, 5)
slice() Creates a slice object. slice(0, 10)
sorted() Returns a sorted list from an iterable. sorted([3, 1]) → [1, 3]
staticmethod() Creates a static method. @staticmethod def method(): pass
str() Converts an object to a string. str(10) → ’10’
super() Returns a proxy for the parent class. super().method()
tuple() Creates a tuple. tuple([1, 2]) → (1, 2)
type() Returns the type of an object. type(5) → <class ‘int’>
vars() Returns the __dict__ attribute of an object. vars(obj)
__import__() Dynamically imports a module. __import__(‘os’)

Mathematical Built-in Functions in Python

 

Python Function Description Example
abs() Returns the absolute (positive) value of a number. abs(-10) → 10
divmod() Returns quotient and remainder as a tuple. divmod(10, 3) → (3, 1)
float() Converts a number or string to a float. float(“3.14”) → 3.14
int() Converts a number or string to an integer. int(3.9) → 3
max() Returns the largest value from the items. max(4, 9, 1) → 9
min() Returns the smallest value from the items. min(4, 9, 1) → 1
pow() Returns x raised to the power y. pow(2, 3) → 8
round() Rounds a number to the nearest integer. round(4.6) → 5
sum() Adds all items in an iterable. sum([1, 2, 3]) → 6
complex() Creates a complex number. complex(2, 3) → (2+3j)

Best Practices for Using Built-in Functions

  • Know the function: The right function has to be used for performing operations such as using the sum() for adding numbers or the len() for counting the items. This helps in saving time.
  • Using built-in functions first: The built-in functions help in performing an operation faster compared to writing the code from scratch.
  • Avoid unnecessary code: The custom functions need not be created when inbuilt functions like max(), abs(), or round are already present to perform a particular operation.
  • Optimise function usage: Multiple functions can be combined, like round(sum(nums)/len(nums)), which helps in calculating the average easily.
  • Check before using: Checking typos must be done before you can use a built-in function. For example, int(“abc”). The use of try-except blocks can help.
  • Write clear code: Using proper and meaningful variable names is very important when using the built-in functions to make the Python code simpler and easier to understand.

Avoiding Repetitive Operations with Built-in Functions in Python

The built-in functions like sum(), max(), and min() are very useful and helpful in avoiding repetitive operations by removing the need for addition of manual loops. These functions help in making the Python code simple, readable, and more efficient. They are also helpful in writing error-free code while saving time with proper logic.

 

Example Without Built-In Function:

Python

Output:

Example Without Built-In Function

 

Explanation: Here, the loop has to be added manually to add up the prices, which can make the code lengthier and less efficient.

 

Example With Built-In Function:

Using sum() to do the same operation:

 

Python

 

Output:

Example With Built-In Function

 

Explanation: Here, the sum() function adds the prices of all items and returns the total in just one line, efficiently.

Real-World Examples for Built-in Functions in Python

1. Analysing Daily Sales Data

The built-in functions can be used for determining the average, the highest, and the lowest sales in a day.

 

Example:

Python

 

Output:

Analysing Daily Sales Data

 

Explanation: Here, sum(), len(), max(), and min() are used to calculate the average, highest, and lowest sales of the day.

2. Cleaning and Sorting Usernames

The built-in function in Python can be used to clean and sort the data.

 

Example:

Python

 Output:

Cleaning and Sorting Usernames

 Explanation: Here, strip(), lower(), sorted(), and list comprehension are used to clean and sort usernames alphabetically.

3. Displaying Product Info from Inventory

The built-in function in Python can be used to find and display the item that has the highest stock in the inventory.

 Example:

Python

 Output:

Displaying Product Info from Inventory

 Explanation: Here, max(), key=, get(), and title() are used to find and format the most stocked product for display.

Learn Python for Free – Build Real Skills Today!
Sign up for our free course and start mastering Python
quiz-icon

Conclusion

The Python built-in functions play a key role in writing cleaner, readable, and efficient code. They are very useful in performing common operations like handling the input, converting the data types, and performing calculations with just a single line of code. Using the built-in functions in Python reduces the repetition and makes the code efficient. They are also helpful in solving real-world issues such as analysing the data, managing the inventory, and many other similar applications. Learning and applying them properly makes Python coding faster and easier.

To take your skills to the next level, enroll in our Python training course and gain hands-on experience. Also, prepare for job interviews with our Python interview questions, designed by industry experts.

About the Author

Technical Research Analyst - Full Stack Development

Kislay is a Technical Research Analyst and Full Stack Developer with expertise in crafting Mobile applications from inception to deployment. Proficient in Android development, IOS development, HTML, CSS, JavaScript, React, Angular, MySQL, and MongoDB, he’s committed to enhancing user experiences through intuitive websites and advanced mobile applications.