Python Functions and Methods: A Topic-by-Topic Reference · Lesson 1 of 12

Lesson 1: Essential Built-in Functions

The built-in functions you use every day: len, type, round, abs, min, max, sum, pow, divmod, range, sorted, any, all and more.

Lesson 1: Essential Built-in Functions

Built-in functions are always available: no import needed. This lesson covers the ones you will use constantly. Each entry shows what it does and the real output of a short example.

Measuring and describing

len(x)

The number of items in a sequence or collection (characters in a string, items in a list, keys in a dictionary).

print(len("Nepal"))
print(len([10, 20, 30]))
print(len({"a": 1, "b": 2}))

Output:

5
3
2

type(x)

The type of a value. Useful when debugging.

print(type(5))
print(type(5.0))
print(type("hi"))
print(type([1]))

Output:

<class 'int'>
<class 'float'>
<class 'str'>
<class 'list'>

isinstance(x, T)

True if x is of type T (or a subclass). Better than comparing type(x) == T.

print(isinstance(5, int))
print(isinstance("5", int))
print(isinstance(5, (int, float)))

Output:

True
False
True

Numbers

abs(x)

The absolute value (distance from zero).

print(abs(-7))
print(abs(3.5))

Output:

7
3.5

round(x, n)

Rounds to n decimal places. Note: Python rounds halves to the nearest even number.

print(round(3.14159, 2))
print(round(2.5))
print(round(3.5))
print(round(1234, -2))

Output:

3.14
2
4
1200

pow(a, b)

a to the power b (same as a ** b). With a third argument it computes a modulus efficiently.

print(pow(2, 10))
print(pow(2, 10, 1000))

Output:

1024
24

divmod(a, b)

The quotient and remainder together, as a tuple.

print(divmod(17, 5))
q, r = divmod(100, 7)
print(q, r)

Output:

(3, 2)
14 2

min(...) and max(...)

The smallest and largest of several values or of an iterable. A key function changes how items are compared.

print(min(4, 9, 2))
print(max([3, 8, 1]))
words = ["kiwi", "banana", "fig"]
print(max(words, key=len))
print(min(words))

Output:

2
8
banana
banana

sum(iterable, start=0)

Adds up the items of an iterable.

print(sum([1, 2, 3, 4]))
print(sum([1.5, 2.5, 3.0]))
print(sum([[1], [2, 3]], []))

Output:

10
7.0
[1, 2, 3]

Counting and checking

range(start, stop, step)

A sequence of numbers, not including stop. Wrap in list() to see it.

print(list(range(5)))
print(list(range(2, 10, 3)))
print(list(range(10, 0, -4)))

Output:

[0, 1, 2, 3, 4]
[2, 5, 8]
[10, 6, 2]

any(iterable) and all(iterable)

any is True if at least one item is true; all is True if every item is true.

marks = [45, 67, 82]
print(all(m >= 40 for m in marks))
print(any(m >= 80 for m in marks))
print(all([]))
print(any([]))

Output:

True
True
True
False

sorted(iterable, key=None, reverse=False)

A new sorted list; the original is untouched. See Lesson 6 for more.

print(sorted([3, 1, 2]))
print(sorted(["b", "A", "c"], key=str.lower))
print(sorted([3, 1, 2], reverse=True))

Output:

[1, 2, 3]
['A', 'b', 'c']
[3, 2, 1]

reversed(seq)

An iterator that walks a sequence backwards. Wrap in list() to see it.

print(list(reversed([1, 2, 3])))
print("".join(reversed("abc")))

Output:

[3, 2, 1]
cba

Converting between types

int(x), float(x), str(x), bool(x)

Convert a value. int("12") works on text of digits; int(3.9) cuts off the decimals.

print(int("12") + 1)
print(int(3.9))
print(float("2.5"))
print(str(99) + " marks")
print(bool(0), bool(""), bool([1]))

Output:

13
3
2.5
99 marks
False False True

list(x), tuple(x), set(x)

Turn any iterable into a list, tuple or set (a set removes duplicates).

print(list("abc"))
print(tuple([1, 2]))
print(set([1, 2, 2, 3, 3]))

Output:

['a', 'b', 'c']
(1, 2)
{1, 2, 3}

bool(x) is False for 0, 0.0, empty text, empty collections and None. Everything else is True. That is why if items: works.

Try it yourself

  1. Use divmod to turn 275 minutes into hours and minutes.
  2. Find the longest word in a sentence with max(..., key=len).
  3. Check with all that every mark in a list is at least 40.

Next lesson: numbers and the math module.

Finished this lesson?Log in to save your progress and pick up where you left off.
Next lesson →

Comments

Loading comments…

MeroSir Team
A free MeroSir course. Run the examples yourself and try the exercises: you learn programming by doing. Spotted a mistake? Use the Report button above the lesson.
Lesson 1: Essential Built-in Functions | MeroSir