10 Must Known Built-In Functions in Python | by Abhay Parashar | in The Pythoneers

10 Must Known Built-In Functions in Python | by Abhay Parashar | in The Pythoneers

This happens to all of us when we are working very hard to write a function that can perform a specific task and later we find out that it is already a built-in function in python. python is full of interesting functions that can save us a lot of time. In this article — we will see 10 of them.

“Never Repeat The work That is Already Done” — Author

1. enumerate

it is a function that will come in handy when you are iterating over an iterator and you want to keep track of the value and the index both. it adds a counter to an iterable and returns it.

Syntax : enumerate(iterable, start=0)

▶ Examples

animals = ['cat','dog','cow'] print(list(enumerate(animals))) ------------------------------------------ [(0, 'cat'), (1, 'dog'), (2, 'cow')]

As the above code example shows enumerate returns index,value both. You can even change the index of the same by specifying the index value after the iterable.

animals = ['cat','dog','cow'] print(list(enumerate(animals,10))) ------------------------------------------ [(10, 'cat'), (11, 'dog'), (12, 'cow')]

We can even combine enumerate with a loop to access the elements and index of an iterable at each iteration.

animals = ['cat','dog','cow'] for index,animal in enumerate(animals):   if animal=='cow':       print(index) --------------------------------------------- 2

It is mostly used for keeping track of the index of items in a sequence.

2. Zip

The zip() function takes iterables as input, aggregates them in a tuple, and returns it. zip can accept any type of iterable such as files, lists, tuples, dictionaries, sets, and so on.

Syntax: zip(*iterables)

Examples

numbers = [1,2,3,4] characters = ['A','B','C','D'] zipped = zip(numbers,characters) print(zipped) print(list(zipped)) -----------------------------------------------  [(1, 'A'), (2, 'B'), (3, 'C'), (4, 'D')] 

In the above example, we have two lists list of numbers and a list of characters. Using the zip function we have combined both the lists into a single iterable. zip function combines bot the iterables and makes a zip object. To retrieve values, we can simply use any iterable such as list, tuple, set, and so on.

You can use the zip function itself to unzip the zipped object to retrieve the starting iterables and values.

numbers = [1,2,3,4] characters = ['A','B','C','D'] zipped = zip(numbers,characters) n,c = zip(*zipped) print(n) print(c) ------------------------------------------ (1, 2, 3, 4) ('A', 'B', 'C', 'D')

3. map

The map() function is used to apply a given function to each item of an iterable. It returns a list of items as result. The map function takes two inputs as a function and an iterable object.

Syntax: map(function,iterable)

Examples

def cube(n):      return n*n*n numbers = [1,2,3,4,5] cubes = list(map(cube,numbers)) print(cubes) --------------------------------- [1,8,27,63,125]

The above example shows how map function can be used to apply a function to an iterable. we can even use map function with an in-build function.

numbers = [1.2324,5.6443,9.4524,6.322] round_numbers = list(map(round,numbers)) print(round_numbers) ------------------------------- [1,6,9,6]

4. Lambda

A Lambda function is also known as an anonymous function because it has no body and doesn’t require def keyword for definition. A Lambda function can have any number of arguments but only one expression in it. The expression evaluates and returned. It has no return statement.

Syntax: lambda arguments:expression

▶ Examples

cube = lambda x:x*x*x numbers = [1,2,3,4,5] cubes = list(map(cube,numbers)) print(cubes) --------------------------------- [1,8,27,63,125]

As the above example shows a lambda function cube is defined, which has one argument and an expression evaluating a cube of a number. we can combine the lambda function with map to perform a specific task on a given iterable without writing an external function as shown on the third line of the code.

5. filter

The filter method filters a given iterable with the help of a function that tests each element in the sequence to be true or not.

Syntax: filter(function,iterable)

Function: the function that tests if each element in a sequence is true or not. Iterable: sequence or iterable that needs to be filtered.

▶ Examples

numbers = [1,2,3,4,5,6,7,8,9,10] check_even = lambda x:x%2==0 even_numbers = list(filter(check_even,numbers)) print(even_numbers) ------------------------------------------ [2,4,6,8,10]

The above code will filter out all the even numbers from the list. here check_even is a lambda function that checks whether a number is even. In the next line using the filter method, we are filtering all the even numbers from the list. It will return the number if it is even, otherwise ignores the number.

“In-Built Functions are boon for programmers” — Author

6. Open

Open function is used to open a file and return a corresponding file object.

Syntax: open(filename, mode, encoding, newline)

filename: it is the path of the file you need to open. mode: while opening a file we can specify different modes to open the file. it defaults open in read mode r means the program only reads the file. There are also many other modes like w will open a file in writing mode, a opens a file in append mode, and so on.

encoding: the encoding format, default it is None newline: how newlines mode works. available values None n r rn ' '

▶ Examples

f = open('data.txt')

Above is a simple code to open a file named data.txt , as you know we can specify the modes while opening a file.

f = open('data.txt', mode='w')

7. ord

ord function takes an integer, character, or a special character as input and returns the ASCII value of it

Syntax: ord(value)

▶ Examples

print(ord('4'))     # Specifying A Integer print(ord('A'))    # Specifying A Character print(ord('@'))    # Specifying A Special Character ----------------------------------------------- 52 65 64

8. Split()

split takes a string as input and returns the given string after breaking it by the specified separator.

Syntax: str.split(seperator,maxsplit)

maxsplit: it is a number that specifies the maximum number to split the string.

▶ Examples:

print('I Love Python'.split()) ------------------------------------------- ['I','Love','Python'] text = 'cat, dog, cow, lion' print(text.split(', ',1)) ----------------------------------------- ['cat', 'dog, cow, lion']

9. any and all

any function returns true if any of the items is True in the given iterable. all return true if all items in an iterable are true otherwise it returns false.

▶ Examples

data = [True, True, False, False, True] print(any(data)) print(all(data)) ---------------------------- True False  data = [True,True,True,True] print(any(data)) print(all(data)) ------------------------------- True True

10. os module

The OS module in Python provides a variety of functions for interacting with the operating system.

▶ Examples

import os print(os.getcwd()) ## Prints the current working directory os.chdir('../')    ## Changes the current working directory os.mkdir()        ## Create a new directory in the current directory os.listdir()      ## List down all the files in the current dir os.remove(FILE_PATH)      ## Remove a file from the current dir os.rename(FILE_PATH)     ## Rename a file in current dir

Thanks For Reading 😀, Follow Me For More here

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top