Python Forum
Python built-ins: when and why should I use them?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Python built-ins: when and why should I use them?
#1
Hello!

I've googled then googled some more, but I still can't seem to find an explanation of when and why I should be using certain built-ins in Python.

I'm about half way through the Python Crash Course book (first attempt at learning programming), and I've been steadily building my own programs that do simple things, like taking inputs and displaying information about a subject, or even a logbook program for the job I currently have.

I feel like I'm doing things that WORK so far, but I feel at the same time that I should be 'classing' my code up and utilizing all the awesome functions that Python already comes with, like functions, classes and more complex loops etc. etc.

I just don't know what the correct usage scenario is for things like that.

Am I perhaps just not writing complex enough code yet to even need most of the built-ins? Should I not even think about this type of stuff? Confused Most of my code right now is just stuff like, get input, compare it to something then return a string, or print this list if a condition is met.

Thanks in advance if anyone takes the time to read this and answer! Heart
Reply
#2
They are pretty well explained in the docs, with quite a few examples: https://docs.python.org/3/library/functions.html
Reply
#3
Definitely have a look at python built-ins and other modules.
Not all at once but there are websites that introduces these one a day and if you
spend 10 min per day looking at a built-in/function/module after a year you gained a lot of knowledge.
And during that time you start using some of these built-ins more often and get used to them.

One example from my own learning experience:
We have two lists and we want to combine the items into one list as pairs.

numbers = [5,2,4,8,1,3,9,7]
letters = ['5','2','4','8','1','3','9','7']
# we want to combine the items in each list into pairs
# [(5, '5'), (2, '2'), (4, '4'), (8, '8'), (1, '1'), (3, '3'), (9, '9'), (7, '7')]
My first solution was this as it reflects the basic knowledge of a beginner
# solution 1
combined = []
for index in range(len(numbers)):
    combined.append((numbers[index], letters[index]))
Then i learned about list comprehensions and was impressed about the simplicity
# more pythonic solution 2 using list comprehension
combined = [(numbers[index], letters[index]) for index in range(len(numbers))]
And then i saw in other code samples that magic function "zip()" and didn´t understand it
Using it with simple examples like this one here i became aquainted to using it in more complex code

# best pythonic solution using list comprehension and zip()
combined = [pair for pair in zip(numbers, letters)]
And if you look at the last code line, isn´t it a beauty?

Without learning about built-ins and using them you don´t evolve, you stagnate.
Reply
#4
In addition to ThomasL excellent answer:

You should never forget that you are standing on shoulders of giants. There have been millions and millions of smart people over decades facing some quite similar problems while coding. Python core developers have solved some of the most common of these problems using some elaborate algorithms (and best coding practices) and included these solutions into Python as built-in functions and/or built-in modules.

So every time you face a coding problem you should ask yourself: 'is this an unique problem faced by handful of people before me or is this fairly common task'. If latter then you definitely should look for some built-in function or module.

You should also look for built-in methods. Some examples of using Python's built-in help

>>> dir(__builtins__)[80:]   # display list of built-in functions
['abs', 'all', 'any', 'ascii', 'bin', 'bool', 'breakpoint', 'bytearray', 'bytes', 
'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 
'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 
'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 
'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license',
'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 
'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 
'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 
'super', 'tuple', 'type', 'vars', 'zip']
>>> help(abs)                # display help of specific built-in function, press q to exit from help
Help on built-in function abs in module builtins:

abs(x, /)
    Return the absolute value of the argument.
(END)
>>> a = list()
>>> a.    # two times tab displays methods you can apply
a.append(   a.copy(     a.extend(   a.insert(   a.remove(   a.sort(     
a.clear(    a.count(    a.index(    a.pop(      a.reverse(
>>> help(a.append)    # or help(list.append)
Help on built-in function append:

append(object, /) method of builtins.list instance
    Append object to the end of the list.
(END)
Python syntax is very close to spoken language and names of functions/methods are quite descriptive giving you good idea what they could do.

To extend ThomasL example of zip one can also do unpacking to achieve same result:

>>> combined = [*zip(numbers, letters)]
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#5
Thank you all for your advice!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Online Python Editors with Built-in Compilers Elon_Warner 0 649 Oct-04-2023, 08:35 PM
Last Post: Elon_Warner

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020