Built-in Functions
We will be discussing some useful built-in functions in this unit. For example, int
,bool
,float
,dict
, etc are all built-in functions.
len()
, min()
, max()
, zip()
functions
len()
: This function returns the length of a String, Dictionary, List, Tuple or Set.min()
: This function returns the minimum possible item from a List.max()
: This function returns the maximum possible item from a List.zip()
: This function zips multiple Lists together, returning a set of Tuples.
Let's see an example:
listExample1 = ['a', 'b', 'c']
listExample2 = [1, 2, 3]
print(zip(listExample1, listExample2))
This would output:
[('a', 1), ('b', 2), ('c', 3)]
For the other functions, practice them using random examples. This will help in practicing better.
map()
function
This function helps us in applying a condition or expression to the entire List, avoiding the use of a messy Loop.
For example, if we want to make a new list with just odd numbers, we would usually use a Loop.
list = range(1,11)
newList = []
for i in list:
if i % 2 != 0:
newList.append(i)
print(newList)
This would output:
[1, 3, 5, 7, 9]
Now, with map()
, we can do this:
objects = range(1,11)
newObjects = list(map(lambda x: x % 2 != 0, objects ))
This will also output:
[1, 3, 5, 7, 9]
filter()
function
This function filters a List. For example, if you have a List of numbers from 1 to 10, and wish to have a new List with the odd numbers, you can use this function.
list = range(1,11)
newList = filter(lambda x: x % 2 != 0, list)
print(newList)
This would output:
[1, 3, 5, 7, 9]
any()
function
This function checks a list of Boolean variables, and returns True
if any one of them is True
. This is the same as the OR
function, where even one True
returns a True
for the entire condition.
list = range(1,10)
if any(map(lambda x:x % 2 == 0, list)):
print("List has even numbers!")
As you can guess, the output is:
List has even numbers!
all()
function
Similar to above, this function serves as the AND
function. In other words, only if all the Boolean variables are True
, it will output True
.
list = range(1,10)
if all(map(lambda x:x % 2 == 0, list)):
print("List has all even numbers!")
else:
print('Failed')
This outputs:
Failed
This is because the list has multiple numbers.