Please support if you like my work by payment through upi: sinhamit@icici or payment by bank
account name: Amit Kumar Sinha,
account number: 2646728782
IFSC code: KKBK0005660
SWIFT: KKBKINBB
enumerate(), zip(), max(), min(), sorted() in Category: Python by amit
🕙 Posted on 2023-09-05 at 17:17:35 Read in Hindi ...
Some More Built-in Functions
enumerate(iterable, start=0)
class enumerate(object) − return an enumerate object. An object supporting iteration.
The enumerate object yields pairs containing a count (from start, which defaults to zero) and a value yielded by the iterable argument.
enumerate is useful for obtaining an indexed list: (0, seq[0]), (1, seq[1]), (2, seq[2]), ...
Example 1
list_1 = ['a', 'b', 'c']
for
index, itemin
enumerate(list_1, start=1):
print( index, item ) # Outputs index number +1 and its respective value of each item/element, as shown below: 1 a
2 b
3 czip(object)
zip(*iterables, strict=False) --> Yield tuples until an input is exhausted.
list(zip('abcdefg', range(3), range(4))) # [('a', 0, 0), ('b', 1, 1), ('c', 2, 2)]
The zip object yields n-length tuples, where n is the number of iterables passed as positional arguments to zip(). The i-th element in every tuple comes from the i-th iterable argument to zip(). This continues until the shortest argument is exhausted. If strict is true and one of the arguments is exhausted before the others, raise a ValueError.
Example 2
list_1 = ['a', 'b', 'c']
list_2 = ['x', 'y', 'z']
zip_obj = zip(list_1, list_2)
print( zip_obj ) # Outputs <zip object at 0x0000013DA8235240>
print( list(zip_obj) ) # Outputs [('a', 'x'), ('b', 'y'), ('c', 'z')]In the above example, if total number of items/
elements in either list_1 or list_2 does not match (that is, those items are more or less), no ERROR will be raised, unless you provide the last argument (after all iterables passed within parentheses) as True. Default value is False for last argument, strict in zip()
built-in function. Only those items are included in output, which are placed in (first) equal index number of all iterables.Example 3
In the following example, you can add variable i inside the first
for
loop, that is, in theprint()
function, before persons[i], and you will get same output asenumerate()
built-in function does. When you uncomment the NESTEDfor
loop, each letter of string data is displayed. You can experiment in various ways, as shown in secondfor
loop of the follwing example.persons = ['abc', 'def', 'ghi', 'jkl', 'mno']
items = ['yz', 'vwx', 'stu', 'pqr']for
iin
range(0, len(persons)):
print(persons[i]) # i is integer data-type
#for
jin
persons[i]:
# print(j)for
iin
items:
print(i, len(i))
for
jin
i:
print(j, len(j))for
index, itemin
enumerate(persons):
print(index, item) # Output will be same as first for loop of this example, if you remove index (variable name) from print function.for
i, jin
zip(persons, items):
print(i, j)The
enumerate()
built-in function is applied on one iterable object, that is, a list or a tuple to fetch its index number and respective value. You can see in Example 1 (shown above), that the start parameter is optional, and when its value is not provided, the index number will start from 0 (zero). See the output of third for loop (herein below) of Example 3.And, the
zip()
built-in function is generally, applied on two iterable objects (you can apply it on three or more iterables), to create a dictionary. These built-in functions and their methods (also of other data-types and modules) are used to avoid manually creation of key:value pairs when large amount of data is processed. A good program is written in such a way that programmers and users write less, do more!Output of first for loop in Example 3
abc
def
ghi
jkl
mnoOutput of second for loop in Example 3
yz 2
y 1
z 1
vwx 3
v 1
w 1
x 1
stu 3
s 1
t 1
u 1
pqr 3
p 1
q 1
r 1Output of third for loop in Example 3
0 abc
1 def
2 ghi
3 jkl
4 mnoOutput of fourth for loop in Example 3
abc yz
def vwx
ghi stu
jkl pqrmin(...)
With a single iterable argument, return its smallest item. The default keyword-only argument specifies an object to return if the provided iterable is empty. With two or more arguments, return the smallest argument.
min(iterable, *[, default=obj, key=func]) -> value
min(arg1, arg2, *args, *[, key=func]) -> value
Example 4
list_1 = ['a', 'b', 'c']
print( min(list_1) ) # Outputs a
print( min( 23, 34, 12, 43, 61, 56 ) ) # Outputs 12max(...)
With a single iterable argument, return its biggest item. The default keyword-only argument specifies an object to return if the provided iterable is empty. With two or more arguments, return the largest argument.
max(iterable, *[, default=obj, key=func]) -> value
max(arg1, arg2, *args, *[, key=func]) -> value
Example 5
list_1 = ['a', 'b', 'c']
print( max(list_1) ) # Outputs c
print( max( 23, 34, 12, 43, 61, 56 ) ) # Outputs 61sorted(iterable, /, *, key=None, reverse=False)
Return a new list containing all items from the iterable in ascending order. A custom key function can be supplied to customize the sort order, and the reverse flag can be set to request the result in descending order.
You can see in Getting Help page (at the bottom), that
sort
list method returns None. But sorted() built-in function returns a new list of same items (after sorting them), as the iterable (list/tuple) passed as argument within the parentheses. sorted()
function creates a new list, when you assign it to a variable name. The original list or tuple is not changed, when you apply the sorted() built-in function to it.my_list = ['d', 'a', 'x', 'm', 'b']
new_list = sorted( my_list )
print( my_list ) # Outputs ['d', 'a', 'x', 'm', 'b']
print( new_list ) # Outputs ['a', 'b', 'd', 'm', 'x']
my_tuple = (34, 23, 5, 62, 7, 1)
new_tuple = sorted( my_tuple )
print( my_tuple ) # Outputs (34, 23, 5, 62, 7, 1)
print( new_tuple ) # Outputs [1, 5, 7, 23, 34, 62]You can see that parameters of sort(self, /, *, key = None, reverse = False) list method is same as of
sorted()
built-in function, except the first parameter. The key parameter can also take a custom function name, and reverse parameter can be True. And, thus the iterable will be sorted accordingly. You will learn about custom function in next pages.slice()
class slice(object) − slice(stop), slice(start, stop[, step])
Create a slice object. This is used for extended slicing (e.g. a[0:10:2]).
S.indices(len) -> (start, stop, stride)
Assuming a sequence of length len, calculate the start and stop indices, and the stride length of the extended slice described by S. Out of bounds indices are clipped in a manner consistent with the handling of normal slices.
- exit()
class Quitter(builtins.object)
- quit()
class Quitter(builtins.object)
You have already seen the slice()
, quit()
and exit()
functions in previous pages. These are mentioned herein to remind you that they are built in function, but rarely used in programs. Shorter form of slice() built-in function, that is, a[0:10:2] is generally used. quit()
and exit()
functions terminate the program immediately, and therefore only used in Python CLI >>>. However, return
keyword is used instead of these two functions.
Leave a Comment:
Amit Sinha March 2nd, 2023 at 9:30 PM
😃 😄 😁 😆 😅 😂 😉 😊 😇 😍 😘 😚 😋 😜 😝 😶 😏 😒 😌 😔 😪 😷 😵 😎 😲 😳 😨 😰 😥 😢 😭 😱 😖 😣 😞 😓 😩 😫 😤
Ribhu March 3rd, 2023 at 9:30 PM
🐵 🐒 🐶 🐩 🐺 🐱 🐯 🐅 🐆 🐴 🐎 🐮 🐂 🐃 🐄 🐷 🐖 🐗 🐽 🐏 🐑 🐐 🐪 🐫 🐘 🐭 🐁 🐀 🐹 🐰 🐇