Must-Know Built-in Python Functions Vol-1
Many of us have noticed after that when we are working or writing with functions that perform specific tasks there is already a built-in function for this specific task, in Python. Python's built-in functions are very useful and easy to use. They make python scripting cleaner and faster. The built-in functions not only save our time but also help us to prevent redundant lines of code.
- Map()
The map function takes a function and one or more iterable objects as an argument then returns an iterator that applied function on the iterable. In other words, the map() function maps or applies the function to each element of the iterable object that we pass in.
syntax:
map(function,iterable(list,tuple etc),....)
Output:<map object at 0x0000020209C55F88>
[1, 4, 9, 16, 25, 36, 49]
How to use lambda function with map()?
Output:
<map at 0x29b5ec67e48>
[1, 4, 27, 256, 3125, 46656, 823543, 16777216, 387420489]
The map() function can take more than one iterable object.
Output:
<map at 0x29b5ec68d88>
[45, 120, 231, 384]
2. enumerate()
The enumerate() is a built-in function that adds a counter to an iterable and returns it. Let’s do an example to understand the concept of this method.
syntax:
enumerate(iterable, start=0)
Output:
[(0, 'Pyhon'), (1, 'Java'), (2, 'Go'), (3, 'Php')]
Here is our code numbering the element of the list according to indexes and then making a list of tuple pairs numbered with indexes. There is an easier way to do this a the enumerate() method.
Output:
<enumerate object at 0x0000018273C3C548>[(0, 'Pyhon'), (1, 'Java'), (2, 'Go'), (3, 'Php')]
You can also specify the start point using with start parameter in enumerate method.
Output:
[(10, 'Pyhon'), (11, 'Java'), (12, 'Go'), (13, 'Php')]
The enumerate() method will make easier your job in both for-loop and list comprehension.
3.reduce()
The reduce() function takes a function and an iterable as value then applies the function the first two elements of iterable, then applies the resulting outcome to the third element, these processes continue until there is one element left.
syntax:
reduce(func, iterable[, initial])
To understand clearly this function let’s look at a quick example;
Output:
187
this diagram shows us clearly how reduce() function works.
Output:
100
100
I encourage you to use the lambda function in your program that makes your code very clear and short.
Thanks for reading. Please let me know if you have any feedback.