Built-in functions#

Overview#

Python has a many built-in functions, installed with your python interpreter, that are readily available for use in your program.

Build-in Function

Meaning

print()

Prints the specified values or variables to the standard output

len()

Returns the length (number of items) of an object, such as a string, list, or tuple

type()

Returns the type of an object, such as int, float, str, list, etc

range()

Generates a sequence of numbers within a specified range

input()

Reads user input from the console as a string

int(), float(), str()

Convert a value to an integer, float, or string, respectively.

sum()

Returns the sum of all items in an iterable

round()

Rounds a number to a specified precision

sorted()

Returns a new sorted list from an iterable

enumerate()

Returns an iterator of tuples containing index and value pairs from an iterable

zip()

Returns an iterator of tuples by aggregating elements from multiple iterables

map()

Applies a given function to each item in an iterable and returns an iterator with the results.

Examples#

len(): Finding the length of an object.

my_list = [1, 2, 3, 4, 5]
length = len(my_list)
print("Length of the list:", length)
Length of the list: 5

type(): Determining the type of an object.

value = 3.14
data_type = type(value)
print("Data type:", data_type)
Data type: <class 'float'>

range(): Generating a sequence of numbers.

numbers = list(range(1, 100))
print(numbers)  # Output: [1, 2, 3, 4, 5]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]

int(), float(), str(): Converting values to specific data types.

num = "10"  # string
num_int = int(num)
print(num_int + 5)  # Output: 15

num_float = float(num)
print(num_float / 2)  # Output: 5.0

text = str(num)
print(text + " is a number")  # Output: "10 is a number"
15
5.0
10 is a number

sum(): Calculating the sum of elements in a list.

numbers = [1, 2, 3, 4, 5]
total = sum(numbers)
print("Sum:", total)
Sum: 15

enumerate is a way to get the index and value in the for loop

msu_majors = ['bme', 'cse', 'bse', 'aetb']
for i, major in enumerate(msu_majors):  # "i" is like a counter, "major" is the list element in each interaction
    print(i," " + major)
0  bme
1  cse
2  bse
3  aetb