Python's built-in functions

Before

--This article is a partial excerpt from a particular chapter of the book "Getting Started with Python Programming" (https://github.com/simon-ritchie/python-novice-book-preview). ――Because it is an introductory book, it is for beginners. --Mainly the contents of the chapter on built-in functions. --Please note that there are some parts that do not match the Qiita article (words such as "chapter" and "page" are used, the number of line breaks is extra, links do not correspond, etc.). If you are interested, please use the e-book version linked above. ――If you give us feedback in comments, we may use and reflect it on the book side as well.

Functions that can be used from the beginning: Python's built-in functions

This chapter touches on some of Python's most commonly used built-in functions. The word built-in may be unfamiliar, but in English the word "built-in" means something like "built-in," "intrinsic," or "built-in."

As you can see from the word built, the word built-in is also used in the building industry, and in the building industry, it refers to the equipment and functions that have already been installed since the building was built.

Built-in is used in the same way in the programming world, and when the expression "Python's built-in functions" appears, it means "functions built in from the beginning in Python".

In the previous chapter, you created various functions yourself, but even if you do not create the basic function processing one by one, Python prepares it in advance. The print function that outputs the contents of variables, etc., which I have used a lot, is also a built-in function of Python.

There are many things that are more convenient to remember than creating your own functions. Let's actually use it little by little and remember it.

Print the contents of the argument: print function

The first is the print function that we have used in various ways up to the previous chapter.

As you can see by using it so far, the print function outputs the contents specified in the argument to the screen. If you run Python on the command line or on a black screen such as Anaconda Prompt, the content will be output to that screen, and if you run it on Jupyter, the content will be output on Jupyter.

It is very often used in various cases such as checking the contents of variables each time, searching for the cause of a defect (bug) (also called debugging), log output, etc. (Log output is Python separately besides print) There is a function in, but I will not touch it here).

The usage is simple, and if you specify an arbitrary value for the argument, the contents will be output.

print(100)

Output contents of code execution result:

100

Although the code has no twist, the result of 100 is output because the value of 100 is specified as an argument in the print function.

You can also specify a variable as an argument. In the code below, a variable called cat_age is specified as an argument of the print function.

cat_age = 5
print(cat_age)

Output contents of code execution result:

5

With this alone, you can check the contents immediately without outputting the contents of the variable, but in practice the code becomes complicated and long, and "What value is this variable now?" Since cases such as "Isn't it?" Often occur, print output is often used.

Also, the print function can specify multiple arguments. In that case, by default, multiple values are output with a half-width space between them. Since it is possible to output without concatenating multiple character strings and variables into one character string, it is convenient when labeling the output contents or handling multiple values. It accepts 2 or 3 arguments or more.

cat_name = 'tama'
print('my name is:', cat_name)

Output contents of code execution result:

my name is: tama

If you want to use a space other than a half-width space as a delimiter when multiple arguments are specified, you can set a space other than the default half-width space by specifying the sep argument using the keyword argument (English). It has the meaning of "delimiter" in the separator).

answer = 2
print('1 + 1', answer, sep=' = ')

Output contents of code execution result:

1 + 1 = 2

Calculate the sum: sum function

The sum function returns the total value of the contents when you specify a list etc. that stores numerical values in the argument. sum is a word that means total or total in Japanese.

In the code below, you can get the same result as when you calculated 1 + 2 + 3 (sum function etc. are mainly used for variables whose values fluctuate such as lists).

summed_val = sum([1, 2, 3])
print(summed_val)

Output contents of code execution result:

6

In addition, the value will be calculated without any problem even if it contains not only integers but also floating point numbers.

summed_val = sum([1.2, 2.5, 3])
print(summed_val)

Output contents of code execution result:

6.7

Calculate maximum and minimum values: max and min functions

Use the max and min functions to find the maximum and minimum values in a list or the like.

The usage is almost the same as the sum function, just specify a list etc. as an argument.

Sample to find the maximum value:

max_value = max([10, 3, 2.5, 60, 30])
print(max_value)

Output contents of code execution result:

60

Sample to find the minimum value:

min_value = min([10, 3, 2.5, 60, 30])
print(min_value)

Output contents of code execution result:

2.5

Get absolute value: abs function

Use the abs function to get the absolute value of a number. The absolute value is ** abs ** olute value in English. If the value specified in the argument is a positive value, the value as it is is returned, and if a negative value is specified in the argument, it is returned as a positive value.

Sample when a positive value is specified for the argument:

absolute_value = abs(10)
print(absolute_value)

Output contents of code execution result:

10

Sample when a negative value is specified for the argument:

absolute_value = abs(-10)
print(absolute_value)

Output contents of code execution result:

10

Performs near rounding calculations: round function

Use the round function to perform near-rounding calculations on floating-point values.

Strictly speaking, as expressed as "close", it is a rounding calculation called "rounding to an even number", which is different from the rounding calculation ("rounding to an even number" is round to even in English. Masu).

"Round to even number" means that when the value of the fraction is 5, the value is set to the side where the result of rounding is even.

For example, consider a value of 2.5, which has a fraction of 5.

Rounded to 3 On the other hand, in the case of rounding to an even number, the result is processed so that it becomes an even number, so it becomes an even number 2.

Think about the value of 1.5 in the same way. When rounded, it becomes 2. Also, rounding to an even number will be converted to an even number 2 in the same way.

Please note that the round function of Python, which is an even-numbered rounding calculation, may be rounded and the result may be different.

Let's actually check the result using the round function in each case.

First, when you specify 1.5, make sure that it becomes an even number of 2.

rounded_value = round(1.5)
print(rounded_value)

Output contents of code execution result:

2

Next, try specifying 1.4. If the fraction is not 5, it will behave like rounding, so it will be 1.

rounded_value = round(1.4)
print(rounded_value)

Output contents of code execution result:

1

Next, try specifying 2.5. The result is 2 instead of 3 because the fraction is 5 and the value is even when rounded.

rounded_value = round(2.5)
print(rounded_value)

Output contents of code execution result:

2

If it is necessary to specify the number of decimal places to use, specify an integer in the second argument. For example, if you want to keep up to the first place, specify 1 for the second argument, and if you want to keep up to the third place, specify 3.

Specified sample to leave up to the first decimal place:

rounded_value = round(100.45235, 1)
print(rounded_value)

Output contents of code execution result:

100.5

Specified sample to leave up to the second place:

rounded_value = round(100.45235, 2)
print(rounded_value)

Output contents of code execution result:

100.45

Specified sample to leave up to the third place:

rounded_value = round(100.45235, 3)
print(rounded_value)

Output contents of code execution result:

100.452

Get the number of elements: len function

Use the len function to get the number of various elements. It is derived from the English word length, which means "length". The type of number that can be acquired depends on the type specified in the argument.

For example, if a character string is specified as an argument, the "number of characters" will be returned. If a list is specified, "the number of values stored in the list" will be returned. If you specify a dictionary, "the number of key / value sets" will be returned, and so on.

Write the code and give it a try.

Let's start with the string. Since the 5-character string ʻapple` is specified in the argument, you can confirm that 5 is returned.

char_num = len('apple')
print(char_num)

Output contents of code execution result:

5

Then try against the list. Since it is a list that stores the three values 100, 200, 300, you can see that 3 is returned.

list_length = len([100, 200, 300])
print(list_length)

Output contents of code execution result:

3

I will also try the dictionary. You can see that the return value is also 2 because there are two sets of keys and values called 'name':'Mike' and two sets of keys and values called 'age': 3.

dict_length = len({'name': 'Mike', 'age': 3})
print(dict_length)

Output contents of code execution result:

2

I mentioned strings, lists, and dictionaries, but you can specify various other types of values as arguments to the len function. However, if you specify a value of a type that does not have a length, an error will occur.

For example, if you try to specify a numerical value such as an integer, you can confirm that an error occurs.

len(100)
TypeError: object of type 'int' has no len()

In this example, the error message means something like "The integer (int) type does not have the function to get the length with the len function".

Get the value of the contents of a list, etc. sorted in ascending order: sorted function

If you use the sorted function for an element that has an order with multiple values such as a list, you can sort (sort the data) the values in ascending order (from the smallest value to the largest value).

As you can see that the function name has ed at the end, it is a function of processing such as "get sorted ** sorted ** value".

If the value specified in the argument is a list containing numerical values, you can get the list arranged in ascending order of numerical values.

sorted_list = sorted([300, 200, 500, 100])
print(sorted_list)

Output contents of code execution result:

[100, 200, 300, 500]

If a list containing a character string is specified as an argument, it will be sorted in alphabetical order (a to z) of the first character in English.

sorted_list = sorted(['banana', 'apple', 'orange', 'melon', 'carrot'])
print(sorted_list)

Output contents of code execution result:

['apple', 'banana', 'carrot', 'melon', 'orange']

If it is a character string that includes a Japanese character string, it will be sorted by hiragana or katakana by the first character.

sorted_list = sorted(['Apple', 'Orange', 'melon', 'carrot', 'Avocado'])
print(sorted_list)

Output contents of code execution result:

['Avocado', 'Orange', 'carrot', 'melon', 'Apple']

You can also sort kanji. The order is fixed, so every time you sort, the order will be the same.

sorted_list = sorted(['Cat', 'dog', 'rabbit'])
print(sorted_list)

Output contents of code execution result:

['rabbit', 'dog', 'Cat']

What kind of rules are used to determine the order of kanji? I will touch on character codes in later chapters, but in reality, characters are assigned something like numbers (Unicode character codes). Hiragana and katakana, various kanji and symbols are assigned something like this number, and when using the sorted function etc., sorting is done with reference to this value.

Note that an error will occur because it is not possible to determine "which is smaller" for a list that contains values of different types such as numbers and character strings.

sorted_list = sorted(
    [300, 'banana', 'apple', 450, 'orange', 'melon', 'carrot', 100])
TypeError: '<' not supported between instances of 'str' and 'int'

I get an error message like "Comparison of less (<) between string and integer elements is not supported".

Get the value of the contents of a list etc. in reverse order: reversed function

Like the sorted function, the reversed function is a function for changing the order of contents such as lists.

This will return the reverse of the values in the list. The name comes from reverse, which means "reverse."

For example, if there is a list of [5, 1, 3], the result of [3, 1, 5] will be returned.

Please note that unlike sorted, the returned value is not a list but a special type called an iterator. If you check the returned value using a function called type that allows you to check the contents of the type that will be mentioned in a later section, you can see that values other than the list are returned.

reversed_list = reversed([300, 200, 500, 100])
print(type(reversed_list))

Output contents of code execution result:

<class 'list_reverseiterator'>

The iterator will be discussed in a later chapter, so I won't explain it here.

The returned iterator cannot be referenced using an index such as [0] like a list. An error will occur as shown below.

reversed_list = reversed([300, 200, 500, 100])
reversed_list[0]
TypeError: 'list_reverseiterator' object is not subscriptable

subscript has the meaning of "subscript". Index numbers such as lists are also called subscripts. Since subscriptable means something like "subscript cannot be set", the error message will be something like "subscript (index cannot be specified) cannot be specified for an object of type list_reverseiterator ".

What if I want to use the returned values as a list? In such a case, you can use it as a list by performing a process called "cast" (cast will be discussed in detail in a later chapter).

To cast to a list, pass the value to the list function. As shown in the code below, you can control the list such as referencing the index by inserting the cast process (in the code below, the line reversed_list = list (reversed_list) corresponds to the cast).

reversed_list = reversed([300, 200, 500, 100])
reversed_list = list(reversed_list)
print('First index value:', reversed_list[0])
print('Values for the entire list:', reversed_list)

Output contents of code execution result:

First index value: 100
Values for the entire list: [100, 500, 200, 300]

Why is it returned as an iterator instead of a list? Even if you look at the posts on the net including overseas, this is clear! I don't really know the reason.

At the time of writing this book, Python has a history of about 30 years, so "the historical convenience of Python implementation" and "sorted are functions, while reversed is actually a class (later). (I will touch), and some of them are classes for ease of implementation in internal C language. "Or" Other built-in functions are also iterators in consideration of load such as memory. There are various things such as "sorted and reversed are out of sync due to changes made from the middle."

It's a little difficult, and I don't think there's any real harm if you don't know it in practice, except that it's interesting to read, so for the time being, just remember "If you want to use the reversed result in a list, cast it." stay here.

Create a string in a specific format: format function

The format function takes a value such as a numerical value in the first argument, and by specifying a character string in a specific format in the second argument, the value specified in the first argument is returned as a character string that matches the specific format. Will do it.

For example, you can put a comma in every 3 digits in a number, round the decimal point at a specific position like the round function, convert it to a character string in a format called binary, or use any number of digits. The beginning is filled with 0 etc.

There are many formats that are used infrequently, and there are some that can be replaced by others, so I will not touch on all formats here, but I will write some code as a sample.

First of all, it is a case where you want to get a character string with a half-width comma added every 3 digits to a numerical value. To use, specify a numeric value for the first argument and a single-byte comma character string for the second argument, such as ','.

print(format(1234567, ','))

Output contents of code execution result:

1,234,567

Next is the character padding process. If you enter a > symbol followed by a half-width number in the second argument, the value of the first argument will be a character string with a half-width space added to the left for that number. For example, if you specify 1 in the first argument and> 5 in the second argument, a character string with four half-width spaces will be returned so that the resulting character string will be 5 characters.

print(format(1, '>5'))

Output contents of code execution result:

    1

If you specify a value such as 123 as the first argument, half-width spaces will be added for the number of insufficient characters, and the number of spaces given will vary depending on the first value.

print(format(123, '>5'))

Output contents of code execution result:

  123

By placing a specific character before the > symbol, you can specify a space other than the space by adding the space for the missing part. For example, if you specify a string such as !> 5 as the second argument, the! Character will be added to the left so that it becomes 5 characters.

print(format(123, '!>5'))

Output contents of code execution result:

!!123

By using this, for example, you can create a character string with 0 added on the left side so that the number of characters is arbitrary.

print(format(12, '0>5'))

Output contents of code execution result:

00012

Also, if you use the < symbol instead of the > symbol, a specific character will be added by the number of characters missing on the right side.

print(format(123, '!<5'))

Output contents of code execution result:

123!!

If you specify the ^ symbol in the second argument instead of the > or < symbol, a specific character string is added to the left and right of the value specified in the first argument, and the total number of characters is specified. The string will be returned in minutes. The number of characters in the result is set after the ^ symbol.

For example, if you want the return value to be 15 characters, specify ^ 15. If you try with the following code, half-width spaces will be added to both sides of the character string "cat`" specified in the first argument until it becomes 15 characters.

print(format('Cat', '^15'))

Output contents of code execution result:

Cat

Also, if you set a specific character to the left of the ^ symbol, additional processing will be executed with that character instead of the half-width space.

print(format('Cat', 'dog^15'))

Output contents of code execution result:

Dog dog dog dog dog dog dog cat dog dog dog dog dog dog dog

Next is the handling of decimal points. To create a string that includes up to a specific number of decimal places with an arbitrary number, specify a string such as .3f as the second argument. The 3 part is an arbitrary value of how many decimal places to leave. If you specify 3, it will remain up to 3rd place. You can set any value, such as .2f or .4f. The part f comes from the acronym float for floating point numbers.

If an integer is specified as the first argument, a character string for the specified number of decimal places, such as .000, will be added.

print(format(2, '.3f'))

Output contents of code execution result:

2.000

If a value such as 1.234567 is specified in the first argument and the number of decimal places specified in the second argument is exceeded, rounding of the fractions is executed and specified in the same way as when using the round function. Only the decimal part of the number of digits is left.

print(format(1.234567, '.2f'))

Output contents of code execution result:

1.23

In addition, you can also convert numbers to binary or hexadecimal numbers. I won't go into too much detail here, but I'm sure some of you will hear them for the first time, so I'll explain them briefly.

You may have seen design images related to computers that are often represented by a list of 0s and 1s (eg, 0011101001, etc.).

The method of expressing various values by combining 0 and 1 in this way is called a binary number. The numbers used in everyday life are called decimal numbers, and the values are expressed using 10 numbers from 0 to 9, such as 0, 1, 2, 3, ...,.

On the other hand, binary numbers are expressed by shifting the combination of 0 and 1 as the value increases, such as 0, 1, 10, 11, 100, 101, 110, 111. It's hard to tell what each value is at first glance, so I rarely use it in my daily life, but it often appears in the world of programming and computers.

As you might expect from the explanation of decimal numbers and decimal numbers, hexadecimal numbers are represented by 16 values. Since there are only 10 numbers from 0 to 9, the 6 alphabets of abcdef (often in uppercase) are used in addition to the numbers.

Hexagonal numbers are mainly used in color codes (color designation) in technologies in the web industry. Colors are represented by numbers and alphabets A to F, such as FFFFFF for white, FF0000 for red, and 0000FF for blue. The left two letters are red, the middle two letters are green, and the right two letters are blue, so you can express the final color, so if you get used to it more than decimal numbers, you can handle colors intuitively. It will be like.

For example, if you express a color in decimal instead of hexadecimal, it seems difficult to judge what color it is just by looking at the numbers such as 16777215 for white, 16711680 for red, and 65280 for green. I will.

Below is a description of what each value is in decimal, binary, and hexadecimal (for hexadecimal numbers that do not have 6 digits, 0 is set to the left in color codes, etc.) For example, if the value is ff, it matches 0000ff on the color code).

The table below summarizes the correspondence between decimal numbers, binary numbers, and hexadecimal numbers.

Decimal number Binary number Hexadecimal
1 1 1
2 10 2
3 11 3
4 100 4
5 101 5
6 110 6
7 111 7
10 1010 a
15 1111 f
16 10000 10
17 10001 11

These conversions can also be done with the format function.

First of all, I will write the process to get the character string converted from decimal number to binary number. To convert to binary, specify 'b' as the second argument. Binary numbers are called binary code, binary number, etc. in English, so the acronym b for binary is used to specify conversion to binary numbers.

Sample to convert decimal 3 to binary 11 string:

print(format(3, 'b'))

Output contents of code execution result:

11

Sample to convert decimal 15 to binary 1111 string:

print(format(15, 'b'))

Output contents of code execution result:

1111

Next, I will touch on the process of acquiring a character string that is converted from a decimal number to a hexadecimal number. To convert to hexadecimal, specify 'x' as the second argument. Hexadecimal numbers are hexadecimal numbers and hexadecimal digits in English, or hex for short. Taking part of the reading of hex, x is now used to specify hexadecimal numbers.

Sample to convert decimal 10 to hexadecimal a string:

print(format(10, 'x'))

Output contents of code execution result:

a

Sample to convert decimal 17 to hexadecimal 11 string:

print(format(17, 'x'))

Output contents of code execution result:

11

Now suppose you want to convert a binary or hexadecimal value to a decimal number. In that case, it is necessary to specify a binary or hexadecimal value as the first argument, but how do you express a binary or hexadecimal value on Python?

First of all, it is a binary number, but to handle it in Python, write the binary number value after prefixing it with 0b. If you want to handle a binary value of 111, express it in the form of 0b111.

Also, when converting to a decimal number, specify 'd' as the second argument. Decimal numbers are called decimal numbers or decimal digits in English, so when specifying a decimal number, take the acronym dicimal and specify d as an argument.

Sample to convert a decimal 111 to a decimal 7 string:

print(format(0b111, 'd'))

Output contents of code execution result:

7

Finally, consider the process of converting a hexadecimal number to a decimal number. To handle hexadecimal numbers in Python, add the value 0x to the beginning. If the value is ffffff, write it as 0xffffff.

The second argument also specifies 'd'.

Sample to convert hexadecimal ffffff to decimal 16777215:

print(format(0xffffff, 'd'))

Output contents of code execution result:

16777215

Check if a variable etc. is of a particular type: isinstance function

Is the value type of a variable etc. a string? Is it an integer? Or is it some other type? If you want to find out such things, use the isinstance function. By using this function, it is possible to control the program such that this process is performed if the value is of type XX, and another process is performed if the value is of type XX.

Although the name comes from, a value generated by some type is called an instance. For example, if the value is 5, it is an instance of an integer because it is a value created from the int type of an integer.

If you think about the meaning of "the target value is an instance of this type" in English, it will be like "target value ** is ** this type ** instance **", so the function name is instance. It has become.

Specify the variable you want to check in the first argument, and specify the type in the second argument.

For example, to check whether the variable named name is a character string, write as follows in the form of specifying str as the second argument. The result is a boolean value (bool) and is returned as True or False. True if the value is of the specified type, False otherwise.

name = 'Tama'
result = isinstance(name, str)
print(result)

Output contents of code execution result:

True

As for the type of the second argument, multiple types can be specified as tuples. In that case, True is returned if it corresponds to "any type in the tuple", and False is returned otherwise. For example, to check whether it corresponds to either an integer (int) or a floating point number (float), specify it as the second argument such as (int, float).

Sample that becomes True if the first argument is an integer:

print(isinstance(100, (int, float)))

Output contents of code execution result:

True

Sample that is True if the first argument is a floating point number:

print(isinstance(20.35, (int, float)))

Output contents of code execution result:

True

Sample that becomes False because it is neither int nor float when the first argument is a string:

print(isinstance('Tama', (int, float)))

Output contents of code execution result:

False

In addition, there is a property that is instance is True even for an instance that inherits a specific type, but that will be discussed in detail in a later class chapter.

Get the type of an instance: type function

I will also touch on the type function that has appeared several times so far. If you specify some instance in the first argument of the type function, the target type will be returned. If you specify an integer value, int is returned, if you specify a character string value, str is returned, and so on.

Example where int is returned with an integer as an argument:

print(type(100))

Output contents of code execution result:

<class 'int'>

Example of str being returned with a string as an argument:

print(type('Cat'))

Output contents of code execution result:

<class 'str'>

Unlike the isinstance function, this can get specific type information, so it is often used in combination with the print function. For example, the isinstance function checks "whether it is a value of a specific type", and if it is different, it is used when "what type of value is it?"

Also, since the type value can be obtained, it is possible to obtain the truth value of the judgment such as "whether this value is the type of XX" as done by isinstance (the writing style of == is the left side). It is written that True is returned if the right side matches, and False is returned if they do not match. It will be described in detail later in the section on conditional branching).

is_int = type(100) == int
print(is_int)

Output contents of code execution result:

True

However, this style of writing is deprecated in PEP8, the Python coding convention, and requires the use of is instance.

Object type comparisons should always use isinstance () instead of direct type comparisons. Python Code Style Guide

There are several reasons. I will touch on some as an example.

First of all, if you only want to compare, is instance is a little less complicated to describe. If you use the isinstance function, you only need to call one function.

The second reason, as mentioned in the isinstance section, is that isinstance includes even if the value inherits a specific type. I'll talk about inheritance later, but imagine a family tree here. A feature called inheritance allows you to create types that inherit the characteristics of their parents.

In the isinstance function, by specifying the ancestor as the type, it will be judged as "whether it is a XX family" (it is actually a program, so it will be judged as "whether it is a character string family"). ..

On the other hand, the type function makes a judgment such as "whether it is a specific individual".

Since it is an old Python version, it does not matter in the Python you are using, but in old Python such as Python 2.7, there is a type that corresponds to the ancestor called basestring as well as str, and as a child, str type and There was also a type called unicode.

When there are multiple types for a specific element (for example, a character string) like this, it is difficult to use the type function when you want to judge whether it is a character string or not. The more similar types there are, such as "str type" or "unicode type", the harder it is to check.

Therefore, one of the merits of isinstance is that you can easily determine whether it is a character string family by simply specifying the ancestor at the top of the family tree with the isinstance function.

Note that in the current version of Python, the string type is unified to str, so you don't have to worry about multiple types of strings. However, such a thing happens with other types, and you will create a specific type (class) yourself in a later chapter, but then you will need the case mentioned this time.

The third reason is that it is close to natural language (ordinary English grammar). Code that is close to natural language is preferred in the Python area. This is because it is easier to understand the code if you can understand the meaning of the code in a way that is similar to reading an English sentence.

For example, as I will explain in detail later in the conditional branching chapter, if you write the code "if the variable is None" in Python, it will be written as ʻif variable is None:`. Although it is a program, you can write code in a form similar to reading English.

In the case of isinstance, it is not so close to natural language, but if you use isinstance to write code such as "if it is a string", it will be code such as ʻif isinstance (variable, str):. .. I personally feel that it is a little closer to natural language than the code such as ʻif type (variable) == str:.

Returns True if all content is True: all function

Use the all function to determine whether all the stored values in a list or tuple are true or false (bool). Since it is a judgment such as "if all is True", the function name is all.

For example, it checks each one and adds the boolean value of the result to the list, and finally it is used to judge whether the whole is True or not.

It's simple to use, just specify a list or tuple containing boolean values as the first argument.

Samples that return True because all the values in the list are True:

all_values_are_true = all([True, True, True, True])
print(all_values_are_true)

Output contents of code execution result:

True

False is returned because False is included in the list Sample:

all_values_are_true = all([True, True, False, True])
print(all_values_are_true)

Output contents of code execution result:

False

Returns True if even one contains True: any function

The content is almost similar to the all function, but the any function returns True if any one of the contents of the list contains True. If you think of the English word "one of them", it would be any of them, but it is an any function because of that meaning.

The usage is the same as the all function, and the list or tuple that stores the boolean value is specified as the first argument.

A sample that returns True because even one True is in the list:

any_values_are_true = any([True, False, False, False])
print(any_values_are_true)

Output contents of code execution result:

True

False is returned because 1 is also True not included in the list Sample:

any_values_are_true = any([False, False, False, False])
print(any_values_are_true)

Output contents of code execution result:

False

Be careful not to overwrite the built-in name

As we've seen, built-in functions use a variety of common and short function names, such as sum and max.

Therefore, if you inadvertently use them for variable names etc., the function will be overwritten. For example, suppose you calculate the value of "sum" and name the variable sum as shown in the code below.

sum = 150 + 200

This code itself does not cause any errors. However, the name sum is overwritten by an integer variable, which makes the built-in sum function unusable.

If you try it, you will get the following error.

sum = 150 + 200
print(sum())
TypeError: 'int' object is not callable

Since sum is not a built-in function but an integer variable, I get an error message saying "An integer object cannot be called (cannot be executed)".

In this way, the name of the built-in function can be used as a variable name etc., but if you overwrite it, you will not be able to use the built-in function, or when someone else edits the code, "I intended to use the built-in function but the variable Overwriting like this example should be avoided as much as possible because it may cause an accident or malfunction due to a case such as "It was overwritten by."

Most Jupyter, or text editors for other programs, have been changed to different text colors so that you can distinguish between built-in functions and regular variables (if this book is also in color). In the code display part, the color of the characters of the built-in function is probably changed). Even if you don't remember all the function names of the built-in functions, be careful if the text color is not the color of the normal variable when you create the variable, and check if it has been overwritten.

Exercises in this chapter Part 1

[1]. Let's create a variable and output its contents.

[2]. Let's calculate the sum of 5 arbitrary numbers with the built-in function without using the + symbol.

[3]. Let's get the maximum value out of 5 numbers using the built-in function.

Exercise example 1 answer example

[1]. Use the print function to print some content such as variables.

age = 25
print('now', age, 'I'm old.')

Output contents of code execution result:

I'm 25 years old now.

[2]. You can calculate the sum of them by specifying a list or tuple that stores numerical values as arguments of the sum function.

list_value = [120, 335.3, 221, 890, 1002]
summed_val = sum(list_value)
print(summed_val)

Output contents of code execution result:

2568.3

[3]. By specifying a list or tuple that stores numerical values as arguments of the max function, you can get the largest value among them.

list_value = [120, 335.3, 221, 890, 1002]
max_value = max(list_value)
print(max_value)

Output contents of code execution result:

1002

Exercises in this chapter Part 2

[1]. Let's get the minimum value out of 5 numbers using the built-in function.

[2]. Let's get the absolute value of -5 using the built-in function.

[3]. Let's calculate even rounding using the built-in function to display the number 100.45 to the first decimal place, and get the value 100.5.

Exercise example 2 answer example

[1]. By specifying a list or tuple that stores numerical values in the argument of the min function, you can get the smallest value among them.

list_value = [120, 335.3, 221, 890, 1002]
min_value = min(list_value)
print(min_value)

Output contents of code execution result:

120

[2]. Use the abs function to get the absolute value of a number. It is convenient to use simply when it is unknown whether the value is positive or negative due to variables.

abs_value = abs(-5)
print(abs_value)

Output contents of code execution result:

5

[3]. Use the round function to perform even rounding, and specify 1 as the second argument to display up to the first decimal place.

rounded_value = round(100.45, 1)
print(rounded_value)

Output contents of code execution result:

100.5

Exercises in this chapter # 3

[1]. Let's use the built-in function to get the number of values in the list [1, 3, 6, 1, 5, 7, 9].

[2]. Let's use the built-in function to get a list of the values in the list [1, 3, 6, 1, 5, 7, 9] sorted in ascending order (in ascending order).

[3]. Let's use the built-in function to get a list of the values in the list [1, 3, 6, 1, 5, 7, 9] sorted in descending order (largest value).

Example of answer to exercise 3

[1]. Use the len function to get the number of values such as lists.

list_length = len([1, 3, 6, 1, 5, 7, 9])
print(list_length)

Output contents of code execution result:

7

[2]. Use the sorted function to get a sorted list in ascending order.

sorted_list = sorted([1, 3, 6, 1, 5, 7, 9])
print(sorted_list)

Output contents of code execution result:

[1, 1, 3, 5, 6, 7, 9]

[3]. To get the list sorted in descending order, reflect the reversed function for the values sorted in ascending order by the sorted function. In addition, the value is further converted into a list, which is called casting.

sorted_list = sorted([1, 3, 6, 1, 5, 7, 9])
reversed_list = list(reversed(sorted_list))
print(reversed_list)

Output contents of code execution result:

[9, 7, 6, 5, 3, 1, 1]

Exercises in this chapter Part 4

[1]. Try using the built-in function to get the boolean value of whether the following variables are strings.

cat_name = 'Tama'

[2]. Try to get the types of the following variables using the built-in function.

price = 200

Exercise example 4 answer example

[1]. Use the isinstance function to get the boolean value of whether a variable etc. is an instance of a specific type. Specify the target instance in the first argument and the type (str because it is a character string this time) in the second argument.

cat_name = 'Tama'
is_str = isinstance(cat_name, str)
print(is_str)

Output contents of code execution result:

True

[2]. Use the type function to get the type of a variable.

price = 200
price_type = type(price)
print(price_type)

Output contents of code execution result:

<class 'int'>

Chapter summary

--A function that is included in Python from the beginning and can be used immediately is called a built-in function in Python. --Use the print function to print the contents of the arguments. --Use the sum function to calculate the total value of a list containing numbers. --Use the max function to get the maximum value, such as a list of numbers, and the min function to get the minimum value. --Use the abs function to get the absolute value of a number. --Use the round function to calculate rounding to an even number (a process close to rounding). --Use the len function to get the number of values such as lists and tuples. --Use the sorted function to get a list of values such as a list sorted in ascending order. --Use the reversed function to get the list values in reverse order. Please note that the return value is not a list, so if you want to treat it as a list, you need to insert a cast. --Use the format function to get a string of numbers or strings processed into a specific format. --Use the isinstance function to check if a variable etc. is of a particular type. --Use the type function to get the type of a variable or the like. --Use the all function to determine if all the values in the list containing boolean values are True. Use the any function to determine if any of the values are True. --Be careful not to create a variable with the same name as the built-in function, as it will cause mistakes.

Appendix

-Introducing all (69) python built-in functions -[Built-in [built-in]](http://e-words.jp/w/%E3%83%93%E3%83%AB%E3%83%88%E3%82%A4%E3%83 % B3.html) --Built-in functions -Rounding decimals and integers in Python round and Decimal.quantize -Rounding-Wikipedia

Recommended Posts

Python's built-in functions
Built-in functions
Wrap Python built-in functions
Examine built-in functions (standard built-in functions) from globals
Built-in python
Conquer 69 Python built-in functions 6th p ~ r
Python functions
Correspondence between Python built-in functions and Rust
List of frequently used built-in functions and methods
Useful Python built-in functions that you use occasionally