Built-in Functions
🔧 Essential Built-in Functions
Python provides many built-in functions that are always available without importing any modules.
Input and Output
python
# print() - output to console
print("Hello, World!")
print("Name:", "Alice", "Age:", 25) # Multiple arguments
print("Python", "is", "awesome", sep="-") # Custom separator
print("Loading", end="...") # Custom end character
# input() - get user input
name = input("Enter your name: ")
age = int(input("Enter your age: "))
print(f"Hello, {name}! You are {age} years old.")Type Conversion Functions
python
# int() - convert to integer
print(int("42")) # 42
print(int(3.14)) # 3
print(int("101", 2)) # 5 (binary to decimal)
# float() - convert to float
print(float("3.14")) # 3.14
print(float(42)) # 42.0
# str() - convert to string
print(str(42)) # "42"
print(str(3.14)) # "3.14"
# bool() - convert to boolean
print(bool(1)) # True
print(bool(0)) # False
print(bool("")) # False
print(bool("hello")) # True
# list(), tuple(), set() - convert to collections
print(list("hello")) # ['h', 'e', 'l', 'l', 'o']
print(tuple([1, 2, 3])) # (1, 2, 3)
print(set([1, 2, 2, 3])) # {1, 2, 3}📊 Mathematical Functions
python
# abs() - absolute value
print(abs(-5)) # 5
print(abs(3.14)) # 3.14
# round() - round to nearest integer
print(round(3.7)) # 4
print(round(3.14159, 2)) # 3.14
# min() and max() - minimum and maximum
print(min(1, 5, 3, 9, 2)) # 1
print(max(1, 5, 3, 9, 2)) # 9
print(min([1, 5, 3, 9, 2])) # 1
# sum() - sum of iterable
print(sum([1, 2, 3, 4, 5])) # 15
print(sum([1, 2, 3], 10)) # 16 (with start value)
# pow() - power function
print(pow(2, 3)) # 8
print(pow(2, 3, 5)) # 3 (2^3 % 5)
# divmod() - quotient and remainder
print(divmod(17, 5)) # (3, 2)📏 Sequence Functions
python
# len() - length of sequence
print(len("hello")) # 5
print(len([1, 2, 3])) # 3
print(len({"a": 1, "b": 2})) # 2
# range() - generate sequence of numbers
print(list(range(5))) # [0, 1, 2, 3, 4]
print(list(range(2, 8))) # [2, 3, 4, 5, 6, 7]
print(list(range(0, 10, 2))) # [0, 2, 4, 6, 8]
# enumerate() - add index to iterable
fruits = ["apple", "banana", "orange"]
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
# zip() - combine multiple iterables
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
for name, age in zip(names, ages):
print(f"{name} is {age} years old")
# reversed() - reverse iterable
print(list(reversed([1, 2, 3, 4]))) # [4, 3, 2, 1]
print(list(reversed("hello"))) # ['o', 'l', 'l', 'e', 'h']🔍 Filtering and Mapping
python
# filter() - filter elements based on condition
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers) # [2, 4, 6, 8, 10]
# map() - apply function to each element
squares = list(map(lambda x: x**2, [1, 2, 3, 4, 5]))
print(squares) # [1, 4, 9, 16, 25]
# Convert strings to integers
string_numbers = ["1", "2", "3", "4", "5"]
int_numbers = list(map(int, string_numbers))
print(int_numbers) # [1, 2, 3, 4, 5]🔍 Inspection Functions
python
# type() - get type of object
print(type(42)) # <class 'int'>
print(type("hello")) # <class 'str'>
print(type([1, 2, 3])) # <class 'list'>
# isinstance() - check if object is instance of class
print(isinstance(42, int)) # True
print(isinstance("hello", str)) # True
print(isinstance([1, 2], list)) # True
# hasattr() - check if object has attribute
class Person:
def __init__(self, name):
self.name = name
person = Person("Alice")
print(hasattr(person, 'name')) # True
print(hasattr(person, 'age')) # False
# getattr() - get attribute value
print(getattr(person, 'name')) # Alice
print(getattr(person, 'age', 'Unknown')) # Unknown (default)
# setattr() - set attribute value
setattr(person, 'age', 25)
print(person.age) # 25
# dir() - list attributes and methods
print(dir(person)) # Lists all attributes and methods📦 Object Creation and Manipulation
python
# vars() - get __dict__ of object
class Student:
def __init__(self, name, grade):
self.name = name
self.grade = grade
student = Student("Bob", "A")
print(vars(student)) # {'name': 'Bob', 'grade': 'A'}
# globals() and locals() - get global and local variables
global_var = "I'm global"
def my_function():
local_var = "I'm local"
print("Globals:", list(globals().keys())[:5]) # First 5 global vars
print("Locals:", locals())
my_function()
# id() - get object identity
a = [1, 2, 3]
b = [1, 2, 3]
c = a
print(id(a)) # Memory address of a
print(id(b)) # Different memory address
print(id(c)) # Same as a🧮 Advanced Functions
python
# all() - check if all elements are True
print(all([True, True, True])) # True
print(all([True, False, True])) # False
print(all([1, 2, 3])) # True (all non-zero)
print(all([1, 0, 3])) # False (0 is falsy)
# any() - check if any element is True
print(any([False, False, False])) # False
print(any([False, True, False])) # True
print(any([0, 0, 0])) # False
print(any([0, 1, 0])) # True
# sorted() - return sorted list
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
print(sorted(numbers)) # [1, 1, 2, 3, 4, 5, 6, 9]
print(sorted(numbers, reverse=True)) # [9, 6, 5, 4, 3, 2, 1, 1]
# Sort strings by length
words = ["apple", "pie", "banana", "cherry"]
print(sorted(words, key=len)) # ['pie', 'apple', 'banana', 'cherry']
# slice() - create slice object
my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
s = slice(2, 8, 2)
print(my_list[s]) # [2, 4, 6]🚀 Practice Examples
Example 1: Data Processing
python
# Process a list of student scores
students = [
{"name": "Alice", "scores": [85, 92, 78, 96]},
{"name": "Bob", "scores": [88, 76, 91, 85]},
{"name": "Charlie", "scores": [92, 88, 84, 90]},
{"name": "Diana", "scores": [95, 87, 92, 89]}
]
# Calculate average score for each student
for student in students:
avg_score = sum(student["scores"]) / len(student["scores"])
student["average"] = round(avg_score, 2)
# Sort students by average score
sorted_students = sorted(students, key=lambda s: s["average"], reverse=True)
# Display results
for i, student in enumerate(sorted_students, 1):
print(f"{i}. {student['name']}: {student['average']}")Example 2: Text Analysis
python
def analyze_text(text):
# Convert to lowercase and split into words
words = text.lower().split()
# Remove punctuation
clean_words = []
for word in words:
clean_word = ''.join(filter(str.isalnum, word))
if clean_word:
clean_words.append(clean_word)
# Count word frequencies
word_count = {}
for word in clean_words:
word_count[word] = word_count.get(word, 0) + 1
# Find most common words
most_common = sorted(word_count.items(), key=lambda x: x[1], reverse=True)
return {
"total_words": len(clean_words),
"unique_words": len(word_count),
"most_common": most_common[:5],
"longest_word": max(clean_words, key=len) if clean_words else "",
"shortest_word": min(clean_words, key=len) if clean_words else ""
}
text = "Python is awesome! Python is powerful and Python is fun to learn."
result = analyze_text(text)
print(f"Total words: {result['total_words']}")
print(f"Unique words: {result['unique_words']}")
print(f"Most common words: {result['most_common']}")
print(f"Longest word: {result['longest_word']}")
print(f"Shortest word: {result['shortest_word']}")Example 3: Number Utilities
python
def number_properties(numbers):
"""Analyze a list of numbers and return various properties"""
# Filter out non-numeric values
valid_numbers = list(filter(lambda x: isinstance(x, (int, float)), numbers))
if not valid_numbers:
return "No valid numbers found"
# Calculate statistics
total = sum(valid_numbers)
count = len(valid_numbers)
average = total / count
# Find extremes
minimum = min(valid_numbers)
maximum = max(valid_numbers)
# Separate positive and negative
positive = list(filter(lambda x: x > 0, valid_numbers))
negative = list(filter(lambda x: x < 0, valid_numbers))
# Check for even/odd (integers only)
integers = list(filter(lambda x: isinstance(x, int), valid_numbers))
even = list(filter(lambda x: x % 2 == 0, integers))
odd = list(filter(lambda x: x % 2 != 0, integers))
return {
"total": total,
"count": count,
"average": round(average, 2),
"minimum": minimum,
"maximum": maximum,
"positive_count": len(positive),
"negative_count": len(negative),
"even_count": len(even),
"odd_count": len(odd)
}
# Test the function
test_numbers = [1, -2, 3.5, 4, -5, 6, 7.2, -8, 9, 0]
result = number_properties(test_numbers)
for key, value in result.items():
print(f"{key}: {value}")Example 4: Validation System
python
def validate_data(data_list, validators):
"""Validate a list of data using multiple validator functions"""
results = []
for i, item in enumerate(data_list):
item_results = {"index": i, "value": item, "valid": True, "errors": []}
for validator_name, validator_func in validators.items():
try:
if not validator_func(item):
item_results["valid"] = False
item_results["errors"].append(validator_name)
except Exception as e:
item_results["valid"] = False
item_results["errors"].append(f"{validator_name}: {str(e)}")
results.append(item_results)
return results
# Define validators
validators = {
"is_string": lambda x: isinstance(x, str),
"not_empty": lambda x: bool(x),
"has_minimum_length": lambda x: len(x) >= 3,
"is_alphanumeric": lambda x: x.isalnum()
}
# Test data
test_data = ["abc", "hello123", "hi", "", "test!", "valid", 123]
# Validate
results = validate_data(test_data, validators)
# Display results
for result in results:
status = "✓" if result["valid"] else "✗"
print(f"{status} Item {result['index']}: '{result['value']}'")
if result["errors"]:
print(f" Errors: {', '.join(result['errors'])}")🎯 Key Takeaways
- Built-in functions are always available without imports
- Type conversion functions help convert between data types
- Mathematical functions provide basic arithmetic operations
- Sequence functions help work with lists, tuples, and strings
- filter() and map() enable functional programming patterns
- Inspection functions help examine objects and their properties
- all() and any() test conditions across sequences
- sorted() creates sorted copies without modifying originals
- Combine built-in functions for powerful data processing
- Understanding built-ins makes Python code more efficient and readable
Continue to: List Comprehensions →