Now let's check out some other important built-in functions that will come in handy such as range()
, enumerate()
, zip()
, sorted()
, filter()
and map()
.
Parameters:
int
]: The start index for iteration, default is 0.int
: The stopping index for iteration, it is a required argument.int
]: Number of indexes to skip on iteration, default is 1.Explanation: This function returns a sequence of length starting from start_index to end_index. The range()
function returns a range object, which is iterable, supports indexing and is immutable. It is mainly used in loops, where a certain number of times a loop should work, like for iterating to the length of an array in C/C++/Java.
## Create a range object of length 20
my_range = range(20)
print(my_range) # range(0,20)
print(type(my_range)) # <class 'range'>
# create a range object with values ranging 5 to 20
print(range(5, 20)) # range(5,20)
# create a range object values ranging 6 to 20 with 2 steps,
# for printing purpose converting 'range' to 'list'
print(list(range(6, 20, 2))) # [6, 8, 10, 12, 14, 16, 18]
## Indexing a range
print(range(20)[0]) # 0
# supports slicing but its not preferred/recommended
print(range(20)[0:10]) # range(0, 10)
## Looping a range object
for var in range(5):
print(var) # [0,1,2,3,4,5]
# reversing the order with step=-1 and end_index=-1
for var in range(5, -1, -1):
print(var) # [4,3,2,1,0]
Parameters:
Explanation: This function returns a enumerate
object given an iterable, each item is a tuple
which contains index & value. The index is in range from 0 to length of the iterable provided and value is an item from that iterable. The enumerate
object is iterable and indexing/slicing is not supported. Similar to range
, enumerate
is mostly used in iteration of loops, but here we use a predefined iterable while creating the object.
## Create a enumerate object from a iterable, say list
my_list = [100, 200, 500, 100]
print(type(enumerate(my_list))) # <class 'enumerate'>
print(list(enumerate(my_list))) # [(0, 100), (1, 200), (2, 500), (3, 100)]
# Checking a item from enumerate, it is a tuple (index, value)
print(list(enumerate(my_list))[0]) # (0,100)
## Looping over the enumerate object
for i, val in enumerate(my_list):
print(i) # 0,1,2,3
print(val) # 100,200,500,100
Parameters:
Explanation: This function returns a zip
object given single/multiple iterables, each item in a zip
is a tuple
which contains n (number of input iterables) length of elements. When provided with multiple iterables, the length of the returned zip
object is equal to the length of the smallest iterable. zip()
is commonly used to unpack values from multiple iterables simultaneously in a loop.
a = ["This", "is", "something"]
b = (14, 3, 6)
c = {34, 7}
## Create a zip object given a iterable
my_zip = zip(a)
print(type(zip(a))) # <class 'zip'>
# create a zip from multiple iterables
print(len(list(zip(a, b, c)))) # 2
# Notice: the length of 'zip' is 2 because smallest is 'c' and
# its length is 2, so remaining values in a & b are ignored
print(list(zip(a, b, c))) # [('This', 14, 34), ('is', 3, 7)]
## Loop over the values
for v in zip(a, b, c):
# 'v' is a tuple with n values, i.e 3 in our case
print(v[0], v[1], v[2]) # [('This', 14, 34), ('is', 3, 7)]
# or unpack them into named variables
for var1, var2 in zip(a, b):
print(var1, var2) # [('This', 14), (is', 3), ('something', 6)]
Parameters:
None
.bool
]: Optional to reverse the sorting, default is False
.Explanation: This function returns a sorted list
given an iterable object. Sorting is O(nLogn). key parameter takes a function which is then used to extract the elements, helpful when an object has some inner structure. sorted()
function has a reverse parameter, which is used to do reverse sorting.
my_string = "ererer"
my_set = {34, 7, 1}
my_tuple = (14, 3, 6)
# Sort a string
print(sorted(my_string)) # ['e', 'e', 'e', 'r', 'r', 'r']
# Sort a set
print(sorted(my_set)) # [1, 7, 34]
# Sort a tuple in reverse order
print(sorted(my_tuple, reverse=True)) # [14, 6, 3]
## Sorting a list with some inner structure using key, example nested lists
my_list = [[10, 20, 56, 23, 12], [200], [2, 7, 23]]
def my_fun(a):
# here return the element you want the iterable to be sort with
# here we are returning length of the nested list
return len(a)
# sort a list by the length of its nested lists
print(sorted(my_list, key=my_fun)) # [[200], [2, 7, 23], [10, 20, 56, 23, 12]]
# Notice: "my_fun" is passed and not called,
# we'll learn about this in the function's section.
Parameters:
Explanation: This function takes an input function & an iterable and applies that function on every item of that iterable. filter()
returns only if True
condition is met, if False
is met nothing is returned, also if no condition is met nothing is returned. filter()
as the name suggests, is used to filter out non-required values from an iterable object. filter()
returns a filter object which is iterable and indexing/slicing is not supported.
## Example: Create simple filter object that filter elements
# which are divisible by 10
# Note: The return value of the filter's function has to be boolean
def my_func(var):
# returns 'True' if number is divisible by 10
if var % 10 == 0:
# value is returned
return True
# value is not returned
return False
my_list = [101, 100, 501, 200]
# Create a filter object
my_filter = filter(my_func, my_list)
print(type(my_filter)) # <class 'filter'>
# convert to a list
print(list(my_filter)) # [100, 200]
# Note: only [100, 200] are returned
# or loop through the filter object
for val in filter(my_func, my_list):
print(val) # [100, 200]
Parameters:
Explanation: This function takes an input function & an iterable object and applies that function on every item of that iterable. As the name suggests, a function is mapped to each element of an iterable. So unlike filter()
, map()
returns the direct value returned by our input function.
## Example 1: Return square of each element in a tuple
my_tuple = (1, 2, 3, 4, 5)
def my_func(var):
# returns square of a number
return var ** 2
# Create a map object
my_mapper = map(my_func, my_tuple)
print(type(my_mapper)) # <class 'map'>
# convert to list to print
print(list(my_mapper)) # [1, 4, 9, 16, 25]
# or looping through map object
for val in map(my_func, my_tuple):
print(val) # [1, 4, 9, 16, 25]