Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Python Functions Tutorial: Working With Functions in Python, Part 2

DZone's Guide to

Python Functions Tutorial: Working With Functions in Python, Part 2

If you're looking to get into the data science field, then knowing Python is imperative. Read on to learn more about Python functions.

· Big Data Zone ·
Free Resource

Learn how to operationalize machine learning and data science projects to monetize your AI initiatives. Download the Gartner report now.

Welcome back! If you missed Part 1, you can check it out here.

Python enumerate() Function

Definition

The enumerate() function adds a counter to an iterable and returns it (the enumerated object).

Syntax

The syntax of enumerate() is:

enumerate(iterable, start=0)

Parameters

The enumerate()function takes two parameters:

  • iterable - a sequence, an iterator, or objects that support iteration.
  • start (optional) - enumerate() starts counting from this number. If start is omitted, 0 is taken as the start.

Example

grocery = ['bread', 'milk', 'butter']
enumerateGrocery = enumerate(grocery)
 
print(type(enumerateGrocery))
 
# converting to list
print(list(enumerateGrocery))
 
# changing the default counter
enumerateGrocery = enumerate(grocery, 10)
print(list(enumerateGrocery))

Output

<class 'enumerate'>
[(0, 'bread'), (1, 'milk'), (2, 'butter')]
[(10, 'bread'), (11, 'milk'), (12, 'butter')]

Python eval() Function

Definition

The eval() function parses the expression passed to this function and runs a Python expression (code) within the program.

Syntax

The syntax of the eval() is:

eval(expression, globals=None, locals=None)

Parameters

eval() takes three parameters:

  • expression - this string is parsed and evaluated as a Python expression.
  • globals(optional) - a dictionary.
  • locals(optional) - a mapping object. Dictionary is the standard and commonly used mapping type in Python.

Example

x = 1
print(eval('x + 1'))

Output

sum = 11

Python filter() Function:

Definition

The filter() function constructs an iterator from elements of an iterable for which a function returns true.

Syntax

The syntax of filter() is:

filter(function, iterable)

Parameters

The filter() function takes two parameters:

  • function - function that tests if elements of an iterable return true or false. If none, the function defaults to the Identity function — which returns false if any elements are false
  • iterable - iterable which is to be filtered, could be sets, lists, tuples, or containers of any iterators.

Example

# list of letters
letters = ['a', 'b', 'd', 'e', 'i', 'j', 'o']
 
# function that filters vowels
def filterVowels(alphabet):
    vowels = ['a', 'e', 'i', 'o', 'u']
 
    if(alphabet in vowels):
        return True
    else:
        return False
 
filteredVowels = filter(filterVowels, letters)
 
print('The filtered vowels are:')
for vowel in filteredVowels:
    print(vowel)

Output

The filtered vowels are:
a
e
i
o

Python getattr() Function:

Definition

The  getattr() function returns the value of the named attribute of an object. If not found, it returns the default value provided to the function.

Syntax

The syntax of getattr() is:

getattr(object, name[, default])

Parameters

The getattr() function takes multiple parameters:

  • object - object whose named attribute's value is to be returned.
  • name - string that contains the attribute's name.
  • default (Optional) - value that is returned when the named attribute is not found.

Example

class Person:
    age = 23
    name = "Adam"
 
person = Person()
print('The age is:', getattr(person, "age"))
print('The age is:', person.age)

Output

The age is: 23
The age is: 23

Python help() Function

Definition

The help() function calls the built-in Python help system.

The syntax of  help() is:

help(object)

Parameters

The help() function takes the maximum of one parameter.

  • object (optional) – you want to generate the help of the given object

Example

>>> help('print')

Python id() Function

Definition

The id() function returns identity (unique integer) of an object.

Syntax

The syntax of id()  is:

id(object)

Parameters

The id() function takes a single parameter object.

Example

class Foo:
    b = 5
 
dummyFoo = Foo()
print('id of dummyFoo =',id(dummyFoo))

Output

id of dummyFoo = 140343867415240

Python len() Function

Definition

The len() function returns the number of items (length) in an object.

Syntax

The syntax of len() is:

len(s)

Parameters

s - a sequence (string, bytes, tuple, list, or range) or a collection (dictionary, set or frozen set)

Example

testList = []
print(testList, 'length is', len(testList))
 
testList = [1, 2, 3]
print(testList, 'length is', len(testList))
 
testTuple = (1, 2, 3)
print(testTuple, 'length is', len(testTuple))
 
testRange = range(1, 10)
print('Length of', testRange, 'is', len(testRange))

Output

[] length is 0
[1, 2, 3] length is 3
(1, 2, 3) length is 3
Length of range(1, 10) is 9

Python max() Function

Definition

The max() function returns the largest element in an iterable or largest of two or more parameters.

Syntax

The syntax of max() is:

max(iterable, *iterables[,key, default])
max(arg1, arg2, *args[, key])

Parameters

max() has two forms of arguments it can work with.

  1. max(iterable, *iterables[, key, default])
    • iterable- sequence (tuple, string), collection (set, dictionary) or an iterator object whose largest element is to be found.
    • *iterables (Optional) - any number of iterables whose largest is to be found.
    • key (Optional) - a key function where the iterables are passed and the comparison is performed based on its return value.
    • default (Optional) - default value if the given iterable is empty.
  2. max(arg1, arg2, *args[, key])
    • arg1 - mandatory first object for comparison (could be number, string or another object).
    • arg2 - mandatory second object for comparison (could be number, string or another object).
    • *args (Optional) - other objects for comparison.
    • key- key function where each argument is passed and the comparison is performed based on its return value

Example

# using max(arg1, arg2, *args)
print('Maximum is:', max(1, 3, 2, 5, 4))
 
# using max(iterable)
num = [1, 3, 2, 8, 5, 10, 6]
print('Maximum is:', max(num))

Output

Maximum is: 5
Maximum is: 10

Python min() Function

Definition

The min() function returns the smallest element in an iterable or smallest of two or more parameters.

The syntax of min() is:

min(iterable, *iterables[,key, default])
min(arg1, arg2, *args[, key])

Parameters

min() has two forms of arguments it can work with.

  1. min(iterable, *iterables[, key, default])
    • iterable- sequence (tuple, string), collection (set, dictionary) or an iterator object whose smallest element is to be found.
    • *iterables (Optional) - any number of iterables whose smallest is to be found.
    • key (Optional) - a key function where the iterables are passed and the comparison is performed based on its return value.
    • default (Optional)- default value if the given iterable is empty.
  2. min(arg1, arg2, *args[, key])
    • arg1 - mandatory first object for comparison (could be number, string or another object)
    • arg2 - mandatory second object for comparison (could be number, string or another object)
    • *args (Optional) - other objects for comparison
    • key - a key function where each argument is passed and a comparison is performed based on its return value

Example

# using min(arg1, arg2, *args)
print('Minimum is:', min(1, 3, 2, 5, 4))
 
# using min(iterable)
num = [3, 2, 8, 5, 10, 6]
print('Minimum is:', min(num))

Output

Minimum is: 1
Minimum is: 2

Python oct() Function

Definition

The oct() function takes an integer number and returns its octal representation. If the given number is an int, it must implement the __index__() method to return an integer.

The syntax of oct() is:

oct(x)

Parameters

The oct() function takes a single parameter x.

This parameter could be:

  • an integer number (binary, decimal or hexadecimal).
  • if not an integer, must implement__index__()method to return an integer.

Example

# decimal number
print('oct(10) is:', oct(10))
 
# binary number
print('oct(0b101) is:', oct(0b101))
 
# hexadecimal number
print('oct(0XA) is:', oct(0XA))

Output

oct(10) is: 0o12
oct(0b101) is: 0o5
oct(0XA) is: 0o12

Python pow() Function

Definition

The pow() function returns x to the power of y. If the third argument (z) is given, it returns x to the power of y modulus z, i.e. pow(x, y) % z.

The syntax of pow() is:

pow(x, y[, z])

Parameters

The pow() function takes three parameters:

  • - number which is to be powered.
  • - number which is to be powered with x.
  • z (Optional) - number which is to be used for modulus operation.

Example

# positive x, positive y (x**y)
print(pow(2, 2))
 
# negative x, positive y
print(pow(-2, 2))
 
# positive x, negative y (x**-y)
print(pow(2, -2))
 
# negative x, negative y
print(pow(-2, -2))

Output

4
4
0.25
0.25

Python reversed() Function

Definition

The reversed() function returns the reversed iterator of the given sequence.

The syntax of  reversed() is:

reversed(seq)

Parameters

The reversed() function takes a single parameter:

  • seq – sequence that should be reversedCould be an object that supports sequence protocol (__len__() and __getitem__() methods) as a tuple, string, list, or range. It could be an object that has implemented __reversed__(). 

Example

# for string
seqString = 'Python'
print(list(reversed(seqString)))
 
# for tuple
seqTuple = ('P', 'y', 't', 'h', 'o', 'n')
print(list(reversed(seqTuple)))
 
# for range
seqRange = range(5, 9)
print(list(reversed(seqRange)))
 
# for list
seqList = [1, 2, 4, 3, 5]
print(list(reversed(seqList)))

Output

['n', 'o', 'h', 't', 'y', 'P']
['n', 'o', 'h', 't', 'y', 'P']
[8, 7, 6, 5]
[5, 3, 4, 2, 1]

Python sum() Function

Definition

The sum() function returns the reversed iterator of the given sequence.

The syntax of sum() is:

sum(iterable, start)

Parameters

  • iterable - iterable (list, tuple, dict, etc) whose item's sum is to be found. Normally, items of the iterable should be numbers.
  • start (optional) - this value is added to the sum of items of the iterable. The default value of start is 0 (if omitted).

Example

numbers = [2.5, 3, 4, -5]
 
# start parameter is not provided
numbersSum = sum(numbers)
print(numbersSum)
 
# start = 10
numbersSum = sum(numbers, 10)
print(numbersSum)

Output

4.5
14.5

Python type() Function

Definition

If a single argument (object) is passed to type(), it returns the type of the given object. If three arguments (name, bases, and dict) are passed, it returns a new type object. The syntax of type() is:

type(object)
type(name, bases, dict)

Parameters

  • If the single object argument is passed to  type(), it returns the type of the given object.

Example

numberList = [1, 2]
print(type(numberList))
 
numberDict = {1: 'one', 2: 'two'}
print(type(numberDict))
 
class Foo:
    a = 0
 
InstanceOfFoo = Foo()
print(type(InstanceOfFoo))

Output

<class 'dict'>
<class 'Foo'>

Next up on this Python functions series, we'll check out the Recursive Function in Python.

Bias comes in a variety of forms, all of them potentially damaging to the efficacy of your ML algorithm. Our Chief Data Scientist discusses the source of most headlines about AI failures here.

Topics:
big data ,python tutorial for beginners ,python functions ,python tutorial

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}