LearnFrenzy
Sign in Take a free test

Python Programming · Topic 23 of 25

Python Built-in Functions Questions and Concepts

  • 4 exercises
  • 50 questions
  • ~60 min
  • Answers explained

Introduction & Syntax

Python Built-in Functions · Study material

Python ships with about 70 built-in functions that are always available without an import: len(), sorted(), zip(), enumerate(), max() with key, any(), round() and many more. Knowing them well replaces dozens of hand-written loops with one clear line – and written tests love their edge cases: round(2.5) is 2, all([]) is True, sum() takes a start value, sorted() returns a list while reversed() returns an iterator. This topic is a practical tour of the built-ins you will use daily, then 50 practice questions run on Python 3.

On this page

  • Numbers: abs, round, pow, divmod, bin, oct, hex
  • Sequences: len, min, max, sum, sorted, reversed, enumerate, zip, range
  • map, filter, any and all
  • Conversions, chr and ord
  • Introspection: type, isinstance, vars, getattr, setattr, hasattr, callable, dir
  • Formatting and iteration: format, repr, iter, next

Number built-ins

abs() gives the absolute value; round(x, n) rounds to n digits (negative n rounds to tens, hundreds…) using round half to even, so round(2.5) is 2 and round(3.5) is 4. Note that round(2.675, 2) gives 2.67 because 2.675 cannot be stored exactly. pow(b, e, m) computes (be) mod m efficiently; divmod(a, b) returns (a // b, a % b). bin(), oct() and hex() give prefixed strings, and int(text, base) converts back.

print(abs(-7.5), abs(-3), abs(3 + 4j))          # absolute value (magnitude for complex)
print(round(3.14159, 2), round(1234.5678, -2))  # negative digits round to tens, hundreds …
print(round(0.5), round(1.5), round(2.5))       # halves go to the EVEN neighbour
print(pow(2, 10), pow(2, 10, 1000), 2 ** -1)    # three-argument pow: (2**10) % 1000
print(divmod(17, 5), divmod(-17, 5))            # (quotient, remainder) with floor division
print(bin(10), oct(8), hex(255), int("ff", 16), int("0b101", 0))

Output

7.5 3 5.0
3.14 1200.0
0 2 2
1024 24 0.5
(3, 2) (-4, 3)
0b1010 0o10 0xff 255 5

Sequence built-ins

min() and max() accept a key= function and a default= for empty input; sum(iterable, start) adds onto a start value (0 by default). sorted() works on any iterable and returns a new list; reversed() returns a lazy iterator. enumerate() pairs items with an index (from start), and zip() pairs several iterables, stopping at the shortest – zip(..., strict=True) (Python 3.10+) raises an error on a length mismatch instead.

marks = [72, 95, 58, 88]
names = ["Ravi", "Asha", "Meera", "Dev"]

print(len(marks), min(marks), max(marks), sum(marks), sum(marks, 100))
print(max(names, key=len), min(names, key=str.lower), max([], default="none"))
print(sorted(marks), sorted(names, reverse=True), marks)    # sorted: new list
print(list(reversed(marks)))                                # reversed: an iterator
print(list(enumerate(names, start=1))[:2])
print(list(zip(names, marks)))
print(list(range(10, 0, -3)), len(range(0, 100, 7)))

Output

4 58 95 313 413
Meera Asha none
[58, 72, 88, 95] ['Ravi', 'Meera', 'Dev', 'Asha'] [72, 95, 58, 88]
[88, 58, 95, 72]
[(1, 'Ravi'), (2, 'Asha')]
[('Ravi', 72), ('Asha', 95), ('Meera', 58), ('Dev', 88)]
[10, 7, 4, 1] 15

map, filter, any and all

map(func, iterable, ...) applies a function to every item (or to items of several iterables in parallel) and filter(func, iterable) keeps the items for which it returns a truthy value – filter(None, …) keeps truthy items. Both return lazy iterators. any() is True if at least one item is truthy and all() if every item is; both short-circuit, and for an empty iterable any is False and all is True.

prices = ["120", "45.5", "300"]
print(list(map(float, prices)))                       # apply a function to every item
print(list(map(pow, [2, 3, 4], [3, 2, 1])))           # map over two iterables
print(list(filter(str.isdigit, ["12", "x", "7", ""])))
print(list(filter(None, [0, 1, "", "a", None, [], [0]])))   # None: keep truthy items

marks = [45, 72, 38, 90]
print(any(m >= 90 for m in marks), all(m >= 40 for m in marks))
print(any([]), all([]))                               # empty: any False, all True

Output

[120.0, 45.5, 300.0]
[8, 9, 4]
['12', '7']
[1, 'a', [0]]
True False
False True

Conversions, chr and ord

The type names are conversion functions: int() (ignores surrounding whitespace, truncates floats toward zero), float(), str(), bool(), list(), tuple(), set(), dict(). ord() gives a character's Unicode code point and chr() goes back.

print(int("  42\n"), int(7.99), int("-0012"), float("1e3"), float(" 3.5 "))
print(str(3.0), str(None), bool(""), bool("0"), bool([0]))
print(list("abc"), tuple([1, 2]), set("aabb") == {"a", "b"})
print(dict([("a", 1), ("b", 2)]), dict(zip("xy", (10, 20))), dict(a=1))
print(chr(65), ord("A"), chr(ord("a") + 25), ord("₹"))

Output

42 7 -12 1000.0 3.5
3.0 None False True True
['a', 'b', 'c'] (1, 2) True
{'a': 1, 'b': 2} {'x': 10, 'y': 20} {'a': 1}
A 65 z 8377

Introspection built-ins

type() returns an object's class and isinstance(obj, cls_or_tuple) checks it (respecting inheritance). vars(obj) shows its attribute dict, dir(obj) lists all reachable names, and getattr(), setattr() and hasattr() work with attributes whose names are strings – getattr(obj, name, default) avoids AttributeError. callable() tells whether something can be called, id() gives an object's identity and help() shows documentation.

class Student:
    school = "LF"
    def __init__(self, name):
        self.name = name

s = Student("Asha")
print(type(s).__name__, isinstance(s, Student), isinstance(3, (int, float)))
print(vars(s), hasattr(s, "name"), hasattr(s, "age"))
print(getattr(s, "school"), getattr(s, "age", "unknown"))   # default avoids AttributeError
setattr(s, "age", 20)                                       # set an attribute by name
print(s.age, callable(s), callable(len), callable(Student))
print([n for n in dir(s) if not n.startswith("_")])
print(id(s) == id(s), type(len).__name__)

Output

Student True True
{'name': 'Asha'} True False
LF unknown
20 False True True
['age', 'name', 'school']
True builtin_function_or_method

Formatting and iteration

format(value, spec) applies the same format specs as f-strings; repr() gives the developer representation (strings get quotes) and ascii() escapes non-ASCII characters. iter() gets an iterator and next(it, default) takes the next item.

print(format(1234567.891, ",.2f"), format(0.256, ".1%"), format(42, "08b"), format(255, "x"))
print(repr("hi"), str("hi"), repr(3.0), repr([1, "a"]))
print(ascii("café ₹"))
data = iter([10, 20])
print(next(data), next(data), next(data, "end"))
print(sorted({"b": 2, "a": 1}), max({"x": 5, "y": 9}, key={"x": 5, "y": 9}.get))

Output

1,234,567.89 25.6% 00101010 ff
'hi' hi 3.0 [1, 'a']
'caf\xe9 \u20b9'
10 20 end
['a', 'b'] y

Common mistakes

  • Naming variables list, str, sum, max, id, input – the built-in is hidden.
  • max() / min() of an empty sequence – ValueError; pass default=.
  • sum() of strings – TypeError; use "".join().
  • Expecting round() to round .5 up – it rounds to even.
  • int() to round money – it truncates; use round().
  • max() of numeric strings – compares as text; use key=int.
  • eval(user_input) – runs arbitrary code; use int(), float() or ast.literal_eval().

Key points to remember

  • round() uses banker's rounding; round(x, -1) rounds to tens.
  • min/max take key= and default=; sum takes a start value.
  • sorted() returns a list; reversed(), map(), filter(), zip(), enumerate() return iterators.
  • any([]) is False; all([]) is True.
  • zip stops at the shortest input unless strict=True.
  • getattr(obj, name, default) never raises AttributeError.
  • Never shadow built-in names; never eval untrusted text.

Frequently asked questions

How can I see every built-in?

dir(__builtins__) in the REPL (or import builtins; dir(builtins)), and help(name) for the documentation of any of them.

Are built-ins faster than my own loops?

Usually yes – sum, min, max, sorted, any and all run in C. They are also clearer.

What should I use instead of eval?

int() and float() for numbers, json.loads() for JSON, and ast.literal_eval() for Python literals such as lists and dicts.

Where can I learn more?

Read Python Functions and The Python Standard Library in the Python tutorial, then practise with the exercises below.

Ready to test your Programming?

Timed online tests with instant scores and explanations.

About this section

About Python Programming

Why it matters

  • Python is the most popular first language and the default for data science, AI, automation and scripting
  • Campus coding rounds and technical interviews increasingly allow – or prefer – Python
  • "Predict the output" questions on lists, strings, dictionaries and mutable defaults are a favourite in written tests
  • Clean Python with comprehensions, generators and OOP is what product companies expect from freshers

Who it is for

  • School students (Class 11–12 computer science with Python) preparing for board exams and practicals
  • College students (B.Tech, BCA, MCA, B.Sc CS) preparing for semester exams, lab work and viva
  • Freshers preparing for campus placements, coding tests and Python interviews
  • Anyone moving into data science, AI or automation who needs strong Python fundamentals

What every topic gives you

  • Study material in five tabs: concepts with runnable examples, coding techniques, programs, interview questions and a cheat sheet
  • Topic-wise MCQs that check your understanding of every concept
  • "Predict the output" puzzles – the trickiest part of written tests
  • "Find the error" programs: syntax errors, runtime exceptions and logical bugs
  • Coding problems with solutions and real output, every one run on Python 3 – open any example in the online Python compiler

Asked in

  • Campus placements
  • TCS, Infosys, Wipro, Accenture tests
  • Python interviews for freshers
  • Data science interviews
  • CBSE / university practicals
  • GATE CS

How to use this section

  1. Read the study material of a topic and run the examples in the browser.
  2. Practise the four exercises – MCQs, output, errors, coding problems – each marked Easy, Medium or Hard, and read every explanation.
  3. Revise with the interview questions and cheat sheet, then move to the next topic.

Search LearnFrenzy

Esc

Quick links