How to Use Built-In Functions in Python?

In this tutorial, I will explain how to use Python built-in functions with detailed examples. During the Python webinar, more questions arrived on how to use built-in functions efficiently, I explored more about built-in functions in Python and I will share my findings in this tutorial. Let us learn more about the built-in function today.

Python Built-In Functions in Python

Python built-in functions are pre-defined functions that are available for use in your code without the need to import any additional modules. These functions provide various functionalities, from basic operations like printing to complex mathematical calculations and data manipulations.

Read Access Modifiers in Python

Commonly Used Python Built-In Functions in Python

Let’s get into some of the most commonly used Python built-in functions with practical examples.

1. print()

The print() function is used to output data to the console. It is one of the most frequently used functions in Python.

Example:

name = "John"
city = "New York"
print(f"Hello, my name is {name} and I live in {city}.")

Output:

Hello, my name is John and I live in New York.

I have executed the above example code and added the screenshot below.

Python Built-In Functions

Check out How to Use Single and Double Quotes in Python?

2. len()

The len() function returns the length of an object, such as a string, list, tuple, or dictionary.

Example:

cities = ["New York", "Los Angeles", "Chicago"]
print(len(cities))

Output:

3

3. type()

The type() function returns the type of an object.

Example:

age = 30
print(type(age))

Output:

<class 'int'>

I have executed the above example code and added the screenshot below.

Use Python Built-In Functions

Read Python 3 vs Python 2 

4. sum()

The sum() function returns the sum of all items in an iterable, such as a list or tuple.

Example:

numbers = [10, 20, 30, 40]
total = sum(numbers)
print(total)

Output:

100

5. max() and min()

The max() and min() functions return the largest and smallest items in an iterable, respectively.

Example:

temperatures = [72, 68, 75, 70, 69]
print(max(temperatures))
print(min(temperatures))

Output:

75
68

I have executed the above example code and added the screenshot below.

How to Use Python Built-In Functions

Check out Difference Between “is None” and “== None” in Python

6. sorted()

The sorted() function returns a new sorted list from the elements of any iterable.

Example:

cities = ["New York", "Los Angeles", "Chicago"]
sorted_cities = sorted(cities)
print(sorted_cities)

Output:

['Chicago', 'Los Angeles', 'New York']

Read How to Comment Out a Block of Code in Python?

7. abs()

The abs() function returns the absolute value of a number.

Example:

temperature_change = -15
print(abs(temperature_change))

Output:

15

I have executed the above example code and added the screenshot below.

How to Use Python Built-In Functions abs()

Check out Difference Between {} and [] in Python

8. round()

The round() function rounds a number to a specified number of decimal places.

Example:

price = 19.98765
print(round(price, 2))

Output:

19.99

9. zip()

The zip() function returns an iterator of tuples, where the first item in each passed iterator is paired together, and then the second item in each passed iterator is paired together, and so on.

Example:

names = ["John", "Jane", "Doe"]
ages = [28, 34, 29]
zipped = zip(names, ages)
print(list(zipped))

Output:

[('John', 28), ('Jane', 34), ('Doe', 29)]

10. filter()

The filter() function constructs an iterator from elements of an iterable for which a function returns true.

Example:

ages = [22, 25, 30, 18, 35]
adults = filter(lambda x: x >= 21, ages)
print(list(adults))

Output:

[22, 25, 30, 35]

Check out Compare Lists, Tuples, Sets, and Dictionaries in Python

Advanced Usage of Python Built-In Functions in Python

Let us learn some advanced usage of built-in functions in Python with examples.

1. Combine Functions for Data Analysis

During my project, I had to analyze a large dataset of customer reviews for a restaurant chain in California. I used several built-in functions to clean, sort, and analyze the data efficiently.

Example:

reviews = [
    {"name": "Alice", "rating": 4.5, "review": "Great food!"},
    {"name": "Bob", "rating": 3.8, "review": "Good service."},
    {"name": "Charlie", "rating": 4.9, "review": "Excellent experience!"}
]

# Extract ratings
ratings = [review["rating"] for review in reviews]

# Calculate average rating
average_rating = sum(ratings) / len(ratings)

# Sort reviews by rating
sorted_reviews = sorted(reviews, key=lambda x: x["rating"], reverse=True)

print(f"Average Rating: {average_rating}")
print("Sorted Reviews:")
for review in sorted_reviews:
    print(f"{review['name']} rated {review['rating']}: {review['review']}")

Output:

Average Rating: 4.4
Sorted Reviews:
Charlie rated 4.9: Excellent experience!
Alice rated 4.5: Great food!
Bob rated 3.8: Good service.

Read Is Python an Object-Oriented Language?

2. Use map() for Efficient Data Transformation

The map() function applies a given function to all items in an input list.

Example:

prices = [19.99, 25.50, 15.75, 22.30]
discounted_prices = map(lambda x: round(x * 0.9, 2), prices)
print(list(discounted_prices))

Output:

[17.99, 22.95, 14.18, 20.07]

3. Handle Exceptions with try and except

Handling exceptions is crucial for building robust applications. The try and except blocks help manage errors gracefully.

Example:

data = ["10", "20", "thirty", "40"]

def convert_to_int(value):
    try:
        return int(value)
    except ValueError:
        return None

converted_data = list(map(convert_to_int, data))
print(converted_data)

Output:

[10, 20, None, 40]

Check out JavaScript vs Python for Web Development: Choosing the Right for Your Project

Conclusion

In this tutorial, I helped you to understand how to use Python built-in functions. I discussed some commonly used built-in functions in Python they are print() , len() , type() , sum() , max() and min() , sorted() , abs() , round() , zip() , filter(). We also discussed some advanced usage of built-in functions in Python they are combining functions for data analysis, use map() for efficient data transformation, and handling exceptions with try and except.

You may also like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.