12 Python In-Built Functions You Should Know

In this article, let us look at the 12 important in-built Functions in Python which helps you to code quickly and easily.

1)append()

The append() function in Python takes a single item as input and appends it to the end of the given list, tuple, or any other set. In Python, append() does not return a new list of items; instead, it returns null. It simply modifies the original list by adding the item at the end.

The length of the list is then increased by one. We can add an item to the list and also add a list to another list. It adds any data type that should be at the end of the list.

Time complexity: O(1).

Syntax:

append(item)

Parameters

  • item: It is the item that is to be added/appended

Example

# Give the list as static input and store it in a variable.
gvn_lst = ["Hello", "this", "is"]

# Pass some random string element as an argument to the append() function 
# and apply it on the given list to add the element at the end of the list
gvn_lst.append("PythonPrograms")

# Print the given list after appending a new list element at the end
print(gvn_lst)

Output:

['Hello', 'this', 'is', 'PythonPrograms']

2)reduce()

The reduce() function in Python iterates through each item in a list or other iterable data type and returns a single value. It is found in the functools library. This is more effective than loop.

Syntax:

reduce(function, iterable)

Parameters

  • function: The function that will be used in the code
  • iterable: The value that will be iterated in the code

Example

# Import reduce() function from functools module using the import keyword
from functools import reduce
def multiply(x, y):
   return x*y
gvn_lst = [2, 3, 5]
print(reduce(multiply, gvn_lst))

Output:

30

3)split():

The split() function is used to split a string into a list of strings by breaking it with the specified separator. The separator can be specified; the default separator is any whitespace.

Syntax:

str.split(separator, maxsplit)

Parameters

  • separator: This is optional. The delimiter at which splits occur. If no separator is specified, the string is split at whitespaces.
  • maxsplit: This is optional. It is the maximum number of splits. There is no limit to the number of splits if it is not provided.

Return Value:

A list of strings is returned by the split() function.

Example

# Give the first string as static input and store it in a variable.
gvn_str1= 'Hello this is pythonprograms'
# Apply split() function on the given first string without 
# passing any separator as an argument
# Here it splits the given string based on the whitespaces by default
print("Splitting gvn_str1:", gvn_str1.split())

# Give the second string as static input and store it in another variable.
gvn_str2 = 'Hello,this,is pythonprograms'

# Apply split() function on the given second string by passing any separator as (,) and maxsplit=1  
# as arguments to it 
# Here it splits the given string containing commas.
# Here 1 specifies we are going to split the first comma as separate element
print("Splitting gvn_str2:", gvn_str2.split(',', 1))

Output:

Splitting gvn_str1: ['Hello', 'this', 'is', 'pythonprograms']
Splitting gvn_str2: ['Hello', 'this,is pythonprograms']

4)Slice():

Based on the specified range, the slice() method returns a portion of an iterable as an object of the slice class. It works with string, list, tuple, set, bytes, or range objects, as well as custom class objects that implement the sequence methods, __getitem__() and __len__().

Syntax:

slice(stop)
slice(start, stop, step)

Parameters

  • start: This is optional. The index at which the iterable’s slicing starts. None is the default value
  • stop: This is the ending index of slicing.
  • step: This is optional. It is the number of steps to jump/increment.

Example

# Give the list as static input and store it in a variable.
gvn_list = [1, 3, 6, 8, 9, 4, 10, 14, 18]


# Pass start, stop as arguments to the slice() function to get the part of the list
# (default stepsize is 1) and store it in a variable.
# Here it returns the list elements in the index range 2 to 6(excluding the last index)
sliceObject_1 = slice(2, 7)

# Pass only the stop value as an argument to the slice() function 
# to get the portion of the list in the given range
# Here start and step values are considered 0, 1 respectively bu default and 
# we get a list elements in the index range 0 to 4
sliceObject_2 = slice(5)

# Slice the given list by passing the start, stop, step values as arguments
# to the slice() function and store it in a variable.
# Here it returnslist elements from index 1 to 7(excluding last index) with the step value 2 
sliceObject_3 = slice(1, 8, 2)
 
# Print the result list elements in the index range 2 to 6
print("The result list elements in the index range 2 to 6: ", gvn_list[sliceObject_1]) 
# Print the result list elements in the index range 0 to 4
print("The result list elements in the index range 0 to 4: ", gvn_list[sliceObject_2])
# Print the result list elements in the index range 1 to 7 with step=2
print("The result list elements in the index range 1 to 7 with step=2: ", gvn_list[sliceObject_3])

Output:

The result list elements in the index range 2 to 6: [6, 8, 9, 4, 10]
The result list elements in the index range 0 to 4: [1, 3, 6, 8, 9]
The result list elements in the index range 1 to 7 with step=2: [3, 8, 4, 14]

5)eval()

The eval() function in Python allows you to perform mathematical operations on integers or floats, even in string form. A mathematical calculation in string format is frequently useful.

The eval() function evaluates the given expression(mathematical or logical). It parses the function, compiles it to bytecode, and then returns the output if a string is passed to it. Because operators have no time complexity, neither does eval.

Syntax:

eval(expression)

Parameters

  • expression: It could be any expression either mathematical or logical

Example

# Give the number as static input and store it in a variable.
gvn_num = 8

# Evaluate the given expression using the eval() function and 
# store it in another variable.
rslt= eval("(gvn_num *9)/2")

# Print the result
print(rslt)

Output:

36.0

6)map()

The map() function, like reduce(), allows you to iterate over each item in an iterable. Map(), on the other hand, operates on each item independently, rather than producing a single result.

Finally, you can use the map() function to perform mathematical operations on two or more lists. It can even be used to manipulate an array of any data type.

Time complexity of the map() = O(n)

Syntax:

map(function, iterable)

Parameters

  • function: The function that will be used in the code
  • iterable: The value that will be iterated in the code
# Create a function which accepts the number as argument and 
# returns the addition of that number with 5 as a result
def add_numbers(gvn_num):
   # Add 5 to the given number and return the result
   return gvn_num+5

# Pass the above add_numbers function and tuple of numbers as arguments to the 
# map() function 
# It will apply the add_numbers function for every element of the list
gvn_num = map(add_numbers, (2, 5, 10, 16))
# Print the result
print(*gvn_num)

Output:

7 10 15 21

7)bin()

The bin() function converts an integer to a binary string prefixing with 0b. Moreover, the integer passed may be negative or positive. For a number n, the time complexity is O(log(n)).

Syntax:

bin(integer)

Parameters

  • integer: It is an integer value passed in order to obtain its binary form.

Example

# Print the binary value of any number by passing it as an argument to the bin() function
# Here we are printing the binary value of 7
print("Binary value of 7 = ", bin(7))

# Here we are printing the binary value of 5
print("Binary value of 5 = ", bin(5))

Output:

Binary value of 7 = 0b111
Binary value of 5 = 0b101

8)enumerate()

The enumerate() function returns the length of an iterable while simultaneously looping through its items. As a result, while printing each item in an iterable data type, it also prints its index.

Assume you want a user to see a list of the items in your database. You can put them in a list and use the enumerate() function to get a numbered list out of it.

Example1

# Give the list as static input and store it in a variable.
gvn_lst = ["hello", "this", "is", "pythonprograms"]

# Loop in the given list with first iterator(i) as index and second iterator as list element value
for i, j in enumerate(gvn_lst):
    print(i, j)

Output:

0 hello
1 this
2 is
3 pythonprograms

Enumerating the list, in addition to being faster, allows you to customize how your numbered items appear.

In fact, by including a start parameter, you can choose to begin numbering from the number you want rather than zero.

Example2

# Give the list as static input and store it in a variable.
gvn_lst = ["hello", "this", "is", "pythonprograms"]

# Pass the given list, start value(from where you want to begin the index number) 
# as arguments to the enumerate() function 
for i, j in enumerate(gvn_lst, start=5):
    print(i, j)

Output:

5 hello
6 this
7 is
8 pythonprograms

9)filter()

The filter() function creates a new iterator that filters elements from an existing one (like list, tuple, or dictionary).

It checks whether the given condition is present in the sequence or not and then prints the result.

Time complexity = O(n).

Syntax:

filter(function, iterable)

Parameters

  • function: The function that will be used in the code
  • iterable: The value that will be iterated in the code
# Give the list as static input and store it in a variable.
gvn_lst = ["hello", "this", "is", "pythonprograms"]
 
   
def vowels(x):
  # Checking whether the first character is vowel
  return x[0].lower() in 'aeiou'

elements = filter(vowels, gvn_lst)

print(list(elements))

Output:

['is']

10)strip()

Strip() in Python removes leading characters from a string. It removes the first character from the string repeatedly if it matches any of the provided characters.

If no character is specified, the strip removes all leading whitespace characters from the string.

# Give the string as static input and store it in a variable.
gvn_str = "pythonprograms"
# Pass a charcter to be stripped/removed from a given as an argument
# to the strip() function and print the result.
# Here it removes/strips the first p character from the given string
rslt = gvn_str.strip("p")
print(rslt)

Output:

ythonprograms

11)exec()

The exec() function executes the specified condition and returns the result in Python expression form.

The Python exec() function runs a dynamically created program, which can be a string or a code object. If it is a string, it is parsed as a Python statement and executed; otherwise, a syntax error is produced.

Syntax:

exec(object[, globals[, locals]])

Parameters

  • object: It could be a string or object code.
  • globals: This is optional. It could be a dictionary.
  • locals: This is optional. It could be a mapping object.

Example

# Give the number as static input and store it in a variable.
gvn_num = 5
# Multiply the given number with 10 and pass it as a string to the exec()
# function to execute the given condition
exec('print(gvn_num*10)')

Output:

50

12)sorted()

The sorted() function returns a sorted list of the given iterable object.

You can sort either in ascending or descending order by specifying it. Numbers are sorted numerically, while strings are sorted alphabetically.

Syntax:

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

Parameters

  • iterable: This is required. It could be any sequence to be sorted like list, dictionary, tuple, etc.
  • key: This is optional. It is a function to execute to decide the order. None is the default value.
  • reverse: This is optional. A Boolean expression. True sorts in ascending, False sorts in descending order. The default value is False.

Example1: Sorting the given list of strings in ascending order

# Give the list of strings as static input and store it in a variable.
gvn_lst = ["r", "c", "e", "h", "v", "s"]

# Pass the given list as an argument to the sorted() function to sort the 
# given list in ascending order alphabetically. 
sorted_lst = sorted(gvn_lst)
# Print the given list after sorting
print("The given list after sorting = ", sorted_lst)

Output:

The given list after sorting = ['c', 'e', 'h', 'r', 's', 'v']

Example2: Sorting the given list of strings in descending order

# Give the list of strings as static input and store it in a variable.
gvn_lst = ["r", "c", "e", "h", "v", "s"]

# Pass the given list, reverse=True as arguments to the sorted() function to sort the 
# given list in descending order alphabetically. 
sorted_lst = sorted(gvn_lst, reverse=True)
# Print the given list after sorting in descending order
print("The given list after sorting in descending order = ", sorted_lst)

Output:

The given list after sorting in descending order = ['v', 's', 'r', 'h', 'e', 'c']

Example3: Sorting the given list of numbers in descending order

# Give the list of numbers as static input and store it in a variable.
gvn_lst = [1, 34, 6, 10, 2, 25, 80]

# Pass the given list, reverse=True as arguments to the sorted() function to sort the 
# given list of numbers in descending order. 
sorted_lst = sorted(gvn_lst, reverse=True)
# Print the given list after sorting in descending order
print("The given list after sorting in descending order = ", sorted_lst)

Output:

The given list after sorting in descending order = [80, 34, 25, 10, 6, 2, 1]