Что делает команда sum в python
Перейти к содержимому

Что делает команда sum в python

  • автор:

Что делает команда sum в python

Sum of numbers in the list is required everywhere. Python provides an inbuilt function sum() which sums up the numbers in the list.

Syntax:

Possible two syntaxes:

Below is the Python implementation of the sum()

Python3

Error and Exceptions

TypeError : This error is raised in the case when there is anything other than numbers in the list.

Python3

So the list should contain numbers Practical Application: Problems where we require sum to be calculated to do further operations such as finding out the average of numbers.

Python3

using for loop

In this , the code first defines a list of numbers. It then initializes a variable called total to 0. The code then iterates through the list using a for loop, and for each number in the list, it adds that number to the total variable. Finally, the code prints the value of total, which is the sum of the numbers in the list.

Python's sum(): The Pythonic Way to Sum Values

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Summing Values the Pythonic Way With sum()

Python’s built-in function sum() is an efficient and Pythonic way to sum a list of numeric values. Adding several numbers together is a common intermediate step in many computations, so sum() is a pretty handy tool for a Python programmer.

As an additional and interesting use case, you can concatenate lists and tuples using sum() , which can be convenient when you need to flatten a list of lists.

In this tutorial, you’ll learn how to:

  • Sum numeric values by hand using general techniques and tools
  • Use Python’s sum() to add several numeric values efficiently
  • Concatenate lists and tuples with sum()
  • Use sum() to approach common summation problems
  • Use appropriate values for the arguments in sum()
  • Decide between sum() and alternative tools to sum and concatenate objects

This knowledge will help you efficiently approach and solve summation problems in your code using either sum() or other alternative and specialized tools.

Free Bonus: Click here to get a Python Cheat Sheet and learn the basics of Python 3, like working with data types, dictionaries, lists, and Python functions.

Understanding the Summation Problem

Summing numeric values together is a fairly common problem in programming. For example, say you have a list of numbers [1, 2, 3, 4, 5] and want to add them together to compute their total sum. With standard arithmetic, you’ll do something like this:

1 + 2 + 3 + 4 + 5 = 15

As far as math goes, this expression is pretty straightforward. It walks you through a short series of additions until you find the sum of all the numbers.

It’s possible to do this particular calculation by hand, but imagine some other situations where it might not be so possible. If you have a particularly long list of numbers, adding by hand can be inefficient and error-prone. What happens if you don’t even know how many items are in the list? Finally, imagine a scenario where the number of items you need to add changes dynamically or unpredictably.

In situations like these, whether you have a long or short list of numbers, Python can be quite useful to solve summation problems.

If you want to sum the numbers by creating your own solution from scratch, then you can try using a for loop:

Here, you first create total and initialize it to 0 . This variable works as an accumulator in which you store intermediate results until you get the final one. The loop iterates through numbers and updates total by accumulating each successive value using an augmented assignment.

You can also wrap the for loop in a function. This way, you can reuse the code for different lists:

In sum_numbers() , you take an iterable—specifically, a list of numeric values—as an argument and return the total sum of the values in the input list. If the input list is empty, then the function returns 0 . The for loop is the same one that you saw before.

You can also use recursion instead of iteration. Recursion is a functional programming technique where a function is called within its own definition. In other words, a recursive function calls itself in a loop:

When you define a recursive function, you take the risk of running into an infinite loop. To prevent this, you need to define both a base case that stops the recursion and a recursive case to call the function and start the implicit loop.

In the above example, the base case implies that the sum of a zero-length list is 0 . The recursive case implies that the total sum is the first value, numbers[0] , plus the sum of the rest of the values, numbers[1:] . Because the recursive case uses a shorter sequence on each iteration, you expect to run into the base case when numbers is a zero-length list. As a final result, you get the sum of all the items in your input list, numbers .

Note: In this example, if you don’t check for an empty input list (your base case), then sum_numbers() will never run into an infinite recursive loop. When your numbers list reaches a length of 0 , the code tries to access an item from the empty list, which raises an IndexError and breaks the loop.

With this kind of implementation, you’ll never get a sum from this function. You’ll get an IndexError every time.

Another option to sum a list of numbers in Python is to use reduce() from functools . To get the sum of a list of numbers, you can pass either operator.add or an appropriate lambda function as the first argument to reduce() :

You can call reduce() with a reduction, or folding, function along with an iterable as arguments. Then reduce() uses the input function to process iterable and returns a single cumulative value.

In the first example, the reduction function is add() , which takes two numbers and adds them together. The final result is the sum of the numbers in the input iterable . As a drawback, reduce() raises a TypeError when you call it with an empty iterable .

In the second example, the reduction function is a lambda function that returns the addition of two numbers.

Since summations like these are commonplace in programming, coding a new function every time you need to sum some numbers is a lot of repetitive work. Additionally, using reduce() isn’t the most readable solution available to you.

Python provides a dedicated built-in function to solve this problem. The function is conveniently called sum() . Since it’s a built-in function, you can use it directly in your code without importing anything.

Getting Started With Python’s sum()

Readability is one of the most important principles behind Python’s philosophy. Visualize what you are asking a loop to do when summing a list of values. You want it to loop over some numbers, accumulate them in an intermediate variable, and return the final sum. However, you can probably imagine a more readable version of summation that doesn’t need a loop. You want Python to take some numbers and sum them together.

Now think about how reduce() does summation. Using reduce() is arguably less readable and less straightforward than even the loop-based solution.

This is why Python 2.3 added sum() as a built-in function to provide a Pythonic solution to the summation problem. Alex Martelli contributed the function, which nowadays is the preferred syntax for summing a list of values:

Wow! That’s neat, isn’t it? It reads like plain English and clearly communicates the action you’re performing on the input list. Using sum() is way more readable than a for loop or a reduce() call. Unlike reduce() , sum() doesn’t raise a TypeError when you provide an empty iterable. Instead, it understandably returns 0 .

You can call sum() with the following two arguments:

  1. iterable is a required argument that can hold any Python iterable. The iterable typically contains numeric values but can also contain lists or tuples.
  2. start is an optional argument that can hold an initial value. This value is then added to the final result. It defaults to 0 .

Internally, sum() adds start plus the values in iterable from left to right. The values in the input iterable are normally numbers, but you can also use lists and tuples. The optional argument start can accept a number, list, or tuple, depending on what is passed to iterable . It can’t take a string.

In the following two sections, you’ll learn the basics of using sum() in your code.

The Required Argument: iterable

Accepting any Python iterable as its first argument makes sum() generic, reusable, and polymorphic. Because of this feature, you can use sum() with lists, tuples, sets, range objects, and dictionaries:

In all these examples, sum() computes the arithmetic sum of all the values in the input iterable regardless of their types. In the two dictionary examples, both calls to sum() return the sum of the keys of the input dictionary. The first example sums the keys by default and the second example sums the keys because of the .keys() call on the input dictionary.

If your dictionary stores numbers in its values and you would like to sum these values instead of the keys, then you can do this by using .values() just like in the .keys() example.

You can also use sum() with a list comprehension as an argument. Here’s an example that computes the sum of the squares of a range of values:

Python 2.4 added generator expressions to the language. Again, sum() works as expected when you use a generator expression as an argument:

This example shows one of the most Pythonic techniques to approach the summation problem. It provides an elegant, readable, and efficient solution in a single line of code.

The Optional Argument: start

The second and optional argument, start , allows you to provide a value to initialize the summation process. This argument is handy when you need to process cumulative values sequentially:

Here, you provide an initial value of 100 to start . The net effect is that sum() adds this value to the cumulative sum of the values in the input iterable. Note that you can provide start as a positional argument or as a keyword argument. The latter option is way more explicit and readable.

If you don’t provide a value to start , then it defaults to 0 . A default value of 0 ensures the expected behavior of returning the total sum of the input values.

Summing Numeric Values

The primary purpose of sum() is to provide a Pythonic way to add numeric values together. Up to this point, you’ve seen how to use the function to sum integer numbers. Additionally, you can use sum() with any other numeric Python types, such as float , complex , decimal.Decimal , and fractions.Fraction .

Here are a few examples of using sum() with values of different numeric types:

Here, you first use sum() with floating-point numbers. It’s worth noting the function’s behavior when you use the special symbols inf and nan in the calls float(«inf») and float(«nan») . The first symbol represents an infinite value, so sum() returns inf . The second symbol represents NaN (not a number) values. Since you can’t add numbers with non-numbers, you get nan as a result.

The other examples sum iterables of complex , Decimal , and Fraction numbers. In all cases, sum() returns the resulting cumulative sum using the appropriate numeric type.

Concatenating Sequences

Even though sum() is mostly intended to operate on numeric values, you can also use the function to concatenate sequences such as lists and tuples. To do that, you need to provide an appropriate value to start :

In these examples, you use sum() to concatenate lists and tuples. This is an interesting feature that you can use to flatten a list of lists or a tuple of tuples. The key requirement for these examples to work is to select an appropriate value for start . For example, if you want to concatenate lists, then start needs to hold a list.

In the examples above, sum() is internally performing a concatenation operation, so it works only with those sequence types that support concatenation, with the exception of strings:

When you try to use sum() to concatenate strings, you get a TypeError . As the exception message suggests, you should use str.join() to concatenate strings in Python. You’ll see examples of using this method later on when you get to the section on Using Alternatives to sum() .

Practicing With Python’s sum()

So far, you’ve learned the basics of working with sum() . You’ve learned how to use this function to add numeric values together and also to concatenate sequences such as lists and tuples.

In this section, you’ll look at some more examples of when and how to use sum() in your code. With these practical examples, you’ll learn that this built-in function is quite handy when you’re performing computations that require finding the sum of a series of numbers as an intermediate step.

You’ll also learn that sum() can be helpful when you’re working with lists and tuples. A special example you’ll look at is when you need to flatten a list of lists.

Computing Cumulative Sums

The first example you’ll code has to do with how to take advantage of the start argument for summing cumulative lists of numeric values.

Say you’re developing a system to manage the sales of a given product at several different points of sale. Every day, you get a sold units report from each point of sale. You need to systematically compute the cumulative sum to know how many units the whole company sold over the week. To solve this problem, you can use sum() :

By using start , you set an initial value to initialize the sum, which allows you to add successive units to the previously computed subtotal. At the end of the week, you’ll have the company’s total count of sold units.

Calculating the Mean of a Sample

Another practical use case of sum() is to use it as an intermediate calculation before doing further calculations. For example, say you need to calculate the arithmetic mean of a sample of numeric values. The arithmetic mean, also known as the average, is the total sum of the values divided by the number of values, or data points, in the sample.

If you have the sample [2, 3, 4, 2, 3, 6, 4, 2] and you want to calculate the arithmetic mean by hand, then you can solve this operation:

(2 + 3 + 4 + 2 + 3 + 6 + 4 + 2) / 8 = 3.25

If you want to speed this up by using Python, you can break it up into two parts. The first part of this computation, where you are adding together the numbers, is a task for sum() . The next part of the operation, where you are dividing by 8, uses the count of numbers in your sample. To calculate your divisor, you can use len() :

Here, the call to sum() computes the total sum of the data points in your sample. Next, you use len() to get the number of data points. Finally, you perform the required division to calculate the sample’s arithmetic mean.

In practice, you may want to turn this code into a function with some additional features, such as a descriptive name and a check for empty samples:

Inside average() , you first check if the input sample has any data points. If not, then you raise a ValueError with a descriptive message. In this example, you use the walrus operator to store the number of data points in the variable num_points so that you won’t need to call len() again. The return statement computes the sample’s arithmetic mean and sends it back to the calling code.

Note: Computing the mean of a sample of data is a common operation in statistics and data analysis. The Python standard library provides a convenient module called statistics to approach these kinds of calculations.

In the statistics module, you’ll find a function called mean() :

The statistics.mean() function has very similar behavior to the average() function you coded earlier. When you call mean() with a sample of numeric values, you’ll get the arithmetic mean of the input data. When you pass an empty list to mean() , you’ll get a statistics.StatisticsError .

Note that when you call average() with a proper sample, you’ll get the desired mean. If you call average() with an empty sample, then you get a ValueError as expected.

Finding the Dot Product of Two Sequences

Another problem you can solve using sum() is finding the dot product of two equal-length sequences of numeric values. The dot product is the algebraic sum of products of every pair of values in the input sequences. For example, if you have the sequences (1, 2, 3) and (4, 5, 6), then you can calculate their dot product by hand using addition and multiplication:

1 × 4 + 2 × 5 + 3 × 6 = 32

To extract successive pairs of values from the input sequences, you can use zip() . Then you can use a generator expression to multiply each pair of values. Finally, sum() can sum the products:

With zip() , you generate a list of tuples with the values from each of the input sequences. The generator expression loops over each tuple while multiplying the successive pairs of values previously arranged by zip() . The final step is to add the products together using sum() .

The code in the above example works. However, the dot product is defined for sequences of equal length, so what happens if you provide sequences with different lengths? In that case, zip() ignores the extra values from the longest sequence, which leads to an incorrect result.

To deal with this possibility, you can wrap the call to sum() in a custom function and provide a proper check for the length of the input sequences:

Here, dot_product() takes two sequences as arguments and returns their corresponding dot product. If the input sequences have different lengths, then the function raises a ValueError .

Embedding the functionality in a custom function allows you to reuse the code. It also gives you the opportunity to name the function descriptively so that the user knows what the function does just by reading its name.

Flattening a List of Lists

Flattening a list of lists is a common task in Python. Say you have a list of lists and need to flatten it into a single list containing all the items from the original nested lists. You can use any of several approaches to flattening lists in Python. For example, you can use a for loop, as in the following code:

Inside flatten_list() , the loop iterates over all the nested lists contained in a_list . Then it concatenates them in flat using an augmented assignment operation ( += ). As the result, you get a flat list with all the items from the original nested lists.

But hold on! You’ve already learned how to use sum() to concatenate sequences in this tutorial. Can you use that feature to flatten a list of lists like you did in the example above? Yes! Here’s how:

That was quick! A single line of code and matrix is now a flat list. However, using sum() doesn’t seem to be the fastest solution.

Using a list comprehension is another common way to flatten a list of list in Python:

This new version of flatten_list() uses a comprehension instead of a regular for loop. However, the nested comprehensions can be challenging to read and understand.

Using .append() is another way to flatten a list of lists:

In this version of flatten_list() , someone reading your code can see that the function iterates over every sublist in a_list . In the second for loop, the function iterates over each item in sublist to finally populate the new flat list with .append() . Arguably, readability can be an advantage of this solution.

Using Alternatives to sum()

As you’ve already learned, sum() is helpful for working with numeric values in general. However, when it comes to working with floating-point numbers, Python provides an alternative tool. In math , you’ll find a function called fsum() that can help you improve the general precision of your floating-point computations.

You might have a task where you want to concatenate or chain several iterables so that you can work with them as one. For this scenario, you can look to the itertools module’s function chain() .

You might also have a task where you want to concatenate a list of strings. You’ve learned in this tutorial that there’s no way to use sum() for concatenating strings. This function just wasn’t built for string concatenation. The most Pythonic alternative is to use str.join() .

Summing Floating-Point Numbers: math.fsum()

If your code is constantly summing floating-point numbers with sum() , then you should consider using math.fsum() instead. This function performs floating-point computations more carefully than sum() , which improves the precision of your computation.

According to its documentation, fsum() “avoids loss of precision by tracking multiple intermediate partial sums.” The documentation provides the following example:

With fsum() , you get a more precise result. However, you should note that fsum() doesn’t solve the representation error in floating-point arithmetic. The following example uncovers this limitation:

In these examples, both functions return the same result. This is due to the impossibility of accurately representing both values 0.1 and 0.2 in binary floating-point:

Unlike sum() , however, fsum() can help you reduce floating-point error propagation when you add very large and very small numbers together:

Wow! The second example is pretty surprising and totally defeats sum() . With sum() , you get 0.0 as a result. This is quite far away from the correct result of 20000.0 , as you get with fsum() .

Concatenating Iterables With itertools.chain()

If you’re looking for a handy tool for concatenating or chaining a series of iterables, then consider using chain() from itertools . This function can take multiple iterables and build an iterator that yields items from the first one, from the second one, and so on until it exhausts all the input iterables:

When you call chain() , you get an iterator of the items from the input iterables. In this example, you access successive items from numbers using next() . If you want to work with a list instead, then you can use list() to consume the iterator and return a regular Python list.

chain() is also a good option for flattening a list of lists in Python:

To flatten a list of lists with chain() , you need to use the iterable unpacking operator ( * ). This operator unpacks all the input iterables so that chain() can work with them and generate the corresponding iterator. The final step is to call list() to build the desired flat list.

Concatenating Strings With str.join()

As you’ve already seen, sum() doesn’t concatenate or join strings. If you need to do so, then the preferred and fastest tool available in Python is str.join() . This method takes a sequence of strings as an argument and returns a new, concatenated string:

Using .join() is the most efficient and Pythonic way to concatenate strings. Here, you use a list of strings as an argument and build a single string from the input. Note that .join() uses the string on which you call the method as a separator during the concatenation. In this example, you call .join() on a string that consists of a single space character ( » » ), so the original strings from greeting are separated by spaces in your final string.

Conclusion

You can now use Python’s built-in function sum() to add multiple numeric values together. This function provides an efficient, readable, and Pythonic way to solve summation problems in your code. If you’re dealing with math computations that require summing numeric values, then sum() can be your lifesaver.

In this tutorial, you learned how to:

  • Sum numeric values using general techniques and tools
  • Add several numeric values efficiently using Python’s sum()
  • Concatenate sequences using sum()
  • Use sum() to approach common summation problems
  • Use appropriate values for the iterable and start arguments in sum()
  • Decide between sum() and alternative tools to sum and concatenate objects

With this knowledge, you’re now able to add multiple numeric values together in a Pythonic, readable, and efficient way.

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Summing Values the Pythonic Way With sum()

Get a short & sweet Python Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team.

Python Tricks Dictionary Merge

About Leodanis Pozo Ramos

Leodanis is an industrial engineer who loves Python and software development. He's a self-taught Python developer with 6+ years of experience. He's an avid technical writer with a growing number of articles published on Real Python and other sites.

Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are:

Python sum()

In this tutorial, we will learn about the Python sum() method with the help of examples.

The sum() function adds the items of an iterable and returns the sum.

Example

sum() Syntax

The syntax of the sum() function is:

The sum() function adds start and items of the given iterable from left to right.

sum() Parameters

  • iterable — iterable (list, tuple, dict, etc). The 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)

sum() Return Value

sum() returns the sum of start and items of the given iterable .

Example: Working of Python sum()

Output

If you need to add floating-point numbers with exact precision, then you should use math.fsum(iterable) instead.

If you need to concatenate items of the given iterable (items must be strings), then you can use the join() method.

Python Built-in Functions

The Python built-in functions are defined as the functions whose functionality is pre-defined in Python. The python interpreter has several functions that are always present for use. These functions are known as Built-in Functions. There are several built-in functions in Python which are listed below:

Python abs() Function

The python abs() function is used to return the absolute value of a number. It takes only one argument, a number whose absolute value is to be returned. The argument can be an integer and floating-point number. If the argument is a complex number, then, abs() returns its magnitude.

Python abs() Function Example

  1. # integer number
  2. integer = -20
  3. print(‘Absolute value of -40 is:’, abs(integer))
  4. # floating number
  5. floating = -20.83
  6. print(‘Absolute value of -40.83 is:’, abs(floating))

Output:

Python all() Function

The python all() function accepts an iterable object (such as list, dictionary, etc.). It returns true if all items in passed iterable are true. Otherwise, it returns False. If the iterable object is empty, the all() function returns True.

Python all() Function Example

  1. # all values true
  2. k = [1, 3, 4, 6]
  3. print(all(k))
  4. # all values false
  5. k = [0, False]
  6. print(all(k))
  7. # one false value
  8. k = [1, 3, 7, 0]
  9. print(all(k))
  10. # one true value
  11. k = [0, False, 5]
  12. print(all(k))
  13. # empty iterable
  14. k = []
  15. print(all(k))

Output:

Python bin() Function

The python bin() function is used to return the binary representation of a specified integer. A result always starts with the prefix 0b.

Python bin() Function Example

  1. x = 10
  2. y = bin(x)
  3. print (y)

Output:

Python bool()

The python bool() converts a value to boolean(True or False) using the standard truth testing procedure.

Python bool() Example

  1. test1 = []
  2. print(test1,’is’,bool(test1))
  3. test1 = [0]
  4. print(test1,’is’,bool(test1))
  5. test1 = 0.0
  6. print(test1,’is’,bool(test1))
  7. test1 = None
  8. print(test1,’is’,bool(test1))
  9. test1 = True
  10. print(test1,’is’,bool(test1))
  11. test1 = ‘Easy string’
  12. print(test1,’is’,bool(test1))

Output:

Python bytes()

The python bytes() in Python is used for returning a bytes object. It is an immutable version of the bytearray() function.

It can create empty bytes object of the specified size.

Python bytes() Example

  1. string = “Hello World.”
  2. array = bytes(string, ‘utf-8’)
  3. print(array)

Output:

Python callable() Function

A python callable() function in Python is something that can be called. This built-in function checks and returns true if the object passed appears to be callable, otherwise false.

Python callable() Function Example

  1. x = 8
  2. print(callable(x))

Output:

Python compile() Function

The python compile() function takes source code as input and returns a code object which can later be executed by exec() function.

Python compile() Function Example

  1. # compile string source to code
  2. code_str = ‘x=5\ny=10\nprint(“sum =”,x+y)’
  3. code = compile(code_str, ‘sum.py’, ‘exec’)
  4. print(type(code))
  5. exec(code)
  6. exec(x)

Output:

Python exec() Function

The python exec() function is used for the dynamic execution of Python program which can either be a string or object code and it accepts large blocks of code, unlike the eval() function which only accepts a single expression.

Python exec() Function Example

  1. x = 8
  2. exec(‘print(x==8)’)
  3. exec(‘print(x+4)’)

Output:

Python sum() Function

As the name says, python sum() function is used to get the sum of numbers of an iterable, i.e., list.

Python sum() Function Example

  1. s = sum([1, 2,4 ])
  2. print(s)
  3. s = sum([1, 2, 4], 10)
  4. print(s)

Output:

Python any() Function

The python any() function returns true if any item in an iterable is true. Otherwise, it returns False.

Python any() Function Example

  1. l = [4, 3, 2, 0]
  2. print(any(l))
  3. l = [0, False]
  4. print(any(l))
  5. l = [0, False, 5]
  6. print(any(l))
  7. l = []
  8. print(any(l))

Output:

Python ascii() Function

The python ascii() function returns a string containing a printable representation of an object and escapes the non-ASCII characters in the string using \x, \u or \U escapes.

Python ascii() Function Example

  1. normalText = ‘Python is interesting’
  2. print(ascii(normalText))
  3. otherText = ‘Pythön is interesting’
  4. print(ascii(otherText))
  5. print(‘Pyth\xf6n is interesting’)

Output:

Python bytearray()

The python bytearray() returns a bytearray object and can convert objects into bytearray objects, or create an empty bytearray object of the specified size.

Python bytearray() Example

  1. string = “Python is a programming language.”
  2. # string with encoding ‘utf-8’
  3. arr = bytearray(string, ‘utf-8’)
  4. print(arr)

Output:

Python eval() Function

The python eval() function parses the expression passed to it and runs python expression(code) within the program.

Python eval() Function Example

  1. x = 8
  2. print(eval(‘x + 1’))

Output:

Python float()

The python float() function returns a floating-point number from a number or string.

Python float() Example

  1. # for integers
  2. print(float(9))
  3. # for floats
  4. print(float(8.19))
  5. # for string floats
  6. print(float(“-24.27”))
  7. # for string floats with whitespaces
  8. print(float(“ -17.19\n”))
  9. # string float error
  10. print(float(“xyz”))

Output:

Python format() Function

The python format() function returns a formatted representation of the given value.

Python format() Function Example

  1. # d, f and b are a type
  2. # integer
  3. print(format(123, “d”))
  4. # float arguments
  5. print(format(123.4567898, “f”))
  6. # binary format
  7. print(format(12, “b”))

Output:

Python frozenset()

The python frozenset() function returns an immutable frozenset object initialized with elements from the given iterable.

Python frozenset() Example

  1. # tuple of letters
  2. letters = (‘m’, ‘r’, ‘o’, ‘t’, ‘s’)
  3. fSet = frozenset(letters)
  4. print(‘Frozen set is:’, fSet)
  5. print(‘Empty frozen set is:’, frozenset())

Output:

Python getattr() Function

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

Python getattr() Function Example

  1. class Details:
  2. age = 22
  3. name = “Phill”
  4. details = Details()
  5. print(‘The age is:’, getattr(details, “age”))
  6. print(‘The age is:’, details.age)

Output:

Python globals() Function

The python globals() function returns the dictionary of the current global symbol table.

A Symbol table is defined as a data structure which contains all the necessary information about the program. It includes variable names, methods, classes, etc.

Python globals() Function Example

  1. age = 22
  2. globals()[‘age’] = 22
  3. print(‘The age is:’, age)

Output:

Python hasattr() Function

The python any() function returns true if any item in an iterable is true, otherwise it returns False.

Python hasattr() Function Example

  1. l = [4, 3, 2, 0]
  2. print(any(l))
  3. l = [0, False]
  4. print(any(l))
  5. l = [0, False, 5]
  6. print(any(l))
  7. l = []
  8. print(any(l))

Output:

Python iter() Function

The python iter() function is used to return an iterator object. It creates an object which can be iterated one element at a time.

Python iter() Function Example

  1. # list of numbers
  2. list = [1,2,3,4,5]
  3. listIter = iter(list)
  4. # prints ‘1’
  5. print(next(listIter))
  6. # prints ‘2’
  7. print(next(listIter))
  8. # prints ‘3’
  9. print(next(listIter))
  10. # prints ‘4’
  11. print(next(listIter))
  12. # prints ‘5’
  13. print(next(listIter))

Output:

Python len() Function

The python len() function is used to return the length (the number of items) of an object.

Python len() Function Example

  1. strA = ‘Python’
  2. print(len(strA))

Output:

Python list()

The python list() creates a list in python.

Python list() Example

  1. # empty list
  2. print(list())
  3. # string
  4. String = ‘abcde’
  5. print(list(String))
  6. # tuple
  7. Tuple = (1,2,3,4,5)
  8. print(list(Tuple))
  9. # list
  10. List = [1,2,3,4,5]
  11. print(list(List))

Output:

Python locals() Function

The python locals() method updates and returns the dictionary of the current local symbol table.

A Symbol table is defined as a data structure which contains all the necessary information about the program. It includes variable names, methods, classes, etc.

Python locals() Function Example

  1. def localsAbsent():
  2. return locals()
  3. def localsPresent():
  4. present = True
  5. return locals()
  6. print(‘localsNotPresent:’, localsAbsent())
  7. print(‘localsPresent:’, localsPresent())

Output:

Python map() Function

The python map() function is used to return a list of results after applying a given function to each item of an iterable(list, tuple etc.).

Python map() Function Example

  1. def calculateAddition(n):
  2. return n+n
  3. numbers = (1, 2, 3, 4)
  4. result = map(calculateAddition, numbers)
  5. print(result)
  6. # converting map object to set
  7. numbersAddition = set(result)
  8. print(numbersAddition)

Output:

Python memoryview() Function

The python memoryview() function returns a memoryview object of the given argument.

Python memoryview () Function Example

  1. #A random bytearray
  2. randomByteArray = bytearray(‘ABC’, ‘utf-8’)
  3. mv = memoryview(randomByteArray)
  4. # access the memory view’s zeroth index
  5. print(mv[0])
  6. # It create byte from memory view
  7. print(bytes(mv[0:2]))
  8. # It create list from memory view
  9. print(list(mv[0:3]))

Output:

Python object()

The python object() returns an empty object. It is a base for all the classes and holds the built-in properties and methods which are default for all the classes.

Python object() Example

  1. python = object()
  2. print(type(python))
  3. print(dir(python))

Output:

Python open() Function

The python open() function opens the file and returns a corresponding file object.

Python open() Function Example

  1. # opens python.text file of the current directory
  2. f = open(“python.txt”)
  3. # specifying full path
  4. f = open(“C:/Python33/README.txt”)

Output:

Python chr() Function

Python chr() function is used to get a string representing a character which points to a Unicode code integer. For example, chr(97) returns the string ‘a’. This function takes an integer argument and throws an error if it exceeds the specified range. The standard range of the argument is from 0 to 1,114,111.

Python chr() Function Example

  1. # Calling function
  2. result = chr(102) # It returns string representation of a char
  3. result2 = chr(112)
  4. # Displaying result
  5. print(result)
  6. print(result2)
  7. # Verify, is it string type?
  8. print(“is it string type:”, type(result) is str)

Output:

Python complex()

Python complex() function is used to convert numbers or string into a complex number. This method takes two optional parameters and returns a complex number. The first parameter is called a real and second as imaginary parts.

Python complex() Example

  1. # Python complex() function example
  2. # Calling function
  3. a = complex(1) # Passing single parameter
  4. b = complex(1,2) # Passing both parameters
  5. # Displaying result
  6. print(a)
  7. print(b)

Output:

Python delattr() Function

Python delattr() function is used to delete an attribute from a class. It takes two parameters, first is an object of the class and second is an attribute which we want to delete. After deleting the attribute, it no longer available in the class and throws an error if try to call it using the class object.

Python delattr() Function Example

  1. class Student:
  2. id = 101
  3. name = “Pranshu”
  4. email = “pranshu@abc.com”
  5. # Declaring function
  6. def getinfo(self):
  7. print(self.id, self.name, self.email)
  8. s = Student()
  9. s.getinfo()
  10. delattr(Student,’course’) # Removing attribute which is not available
  11. s.getinfo() # error: throws an error

Output:

Python dir() Function

Python dir() function returns the list of names in the current local scope. If the object on which method is called has a method named __dir__(), this method will be called and must return the list of attributes. It takes a single object type argument.

Python dir() Function Example

  1. # Calling function
  2. att = dir()
  3. # Displaying result
  4. print(att)

Output:

Python divmod() Function

Python divmod() function is used to get remainder and quotient of two numbers. This function takes two numeric arguments and returns a tuple. Both arguments are required and numeric

Python divmod() Function Example

  1. # Python divmod() function example
  2. # Calling function
  3. result = divmod(10,2)
  4. # Displaying result
  5. print(result)

Output:

Python enumerate() Function

Python enumerate() function returns an enumerated object. It takes two parameters, first is a sequence of elements and the second is the start index of the sequence. We can get the elements in sequence either through a loop or next() method.

Python enumerate() Function Example

  1. # Calling function
  2. result = enumerate([1,2,3])
  3. # Displaying result
  4. print(result)
  5. print(list(result))

Output:

Python dict()

Python dict() function is a constructor which creates a dictionary. Python dictionary provides three different constructors to create a dictionary:

  • If no argument is passed, it creates an empty dictionary.
  • If a positional argument is given, a dictionary is created with the same key-value pairs. Otherwise, pass an iterable object.
  • If keyword arguments are given, the keyword arguments and their values are added to the dictionary created from the positional argument.

Python dict() Example

  1. # Calling function
  2. result = dict() # returns an empty dictionary
  3. result2 = dict(a=1,b=2)
  4. # Displaying result
  5. print(result)
  6. print(result2)

Output:

Python filter() Function

Python filter() function is used to get filtered elements. This function takes two arguments, first is a function and the second is iterable. The filter function returns a sequence of those elements of iterable object for which function returns true value.

The first argument can be none, if the function is not available and returns only elements that are true.

Python filter() Function Example

  1. # Python filter() function example
  2. def filterdata(x):
  3. if x>5:
  4. return x
  5. # Calling function
  6. result = filter(filterdata,(1,2,6))
  7. # Displaying result
  8. print(list(result))

Output:

Python hash() Function

Python hash() function is used to get the hash value of an object. Python calculates the hash value by using the hash algorithm. The hash values are integers and used to compare dictionary keys during a dictionary lookup. We can hash only the types which are given below:

Hashable types: * bool * int * long * float * string * Unicode * tuple * code object.

Python hash() Function Example

  1. # Calling function
  2. result = hash(21) # integer value
  3. result2 = hash(22.2) # decimal value
  4. # Displaying result
  5. print(result)
  6. print(result2)

Output:

Python help() Function

Python help() function is used to get help related to the object passed during the call. It takes an optional parameter and returns help information. If no argument is given, it shows the Python help console. It internally calls python’s help function.

Python help() Function Example

  1. # Calling function
  2. info = help() # No argument
  3. # Displaying result
  4. print(info)

Output:

Python min() Function

Python min() function is used to get the smallest element from the collection. This function takes two arguments, first is a collection of elements and second is key, and returns the smallest element from the collection.

Python min() Function Example

  1. # Calling function
  2. small = min(2225,325,2025) # returns smallest element
  3. small2 = min(1000.25,2025.35,5625.36,10052.50)
  4. # Displaying result
  5. print(small)
  6. print(small2)

Output:

Python set() Function

In python, a set is a built-in class, and this function is a constructor of this class. It is used to create a new set using elements passed during the call. It takes an iterable object as an argument and returns a new set object.

Python set() Function Example

  1. # Calling function
  2. result = set() # empty set
  3. result2 = set(‘12’)
  4. result3 = set(‘javatpoint’)
  5. # Displaying result
  6. print(result)
  7. print(result2)
  8. print(result3)

Output:

Python hex() Function

Python hex() function is used to generate hex value of an integer argument. It takes an integer argument and returns an integer converted into a hexadecimal string. In case, we want to get a hexadecimal value of a float, then use float.hex() function.

Python hex() Function Example

  1. # Calling function
  2. result = hex(1)
  3. # integer value
  4. result2 = hex(342)
  5. # Displaying result
  6. print(result)
  7. print(result2)

Output:

Python id() Function

Python id() function returns the identity of an object. This is an integer which is guaranteed to be unique. This function takes an argument as an object and returns a unique integer number which represents identity. Two objects with non-overlapping lifetimes may have the same id() value.

Python id() Function Example

  1. # Calling function
  2. val = id(“Javatpoint”) # string object
  3. val2 = id(1200) # integer object
  4. val3 = id([25,336,95,236,92,3225]) # List object
  5. # Displaying result
  6. print(val)
  7. print(val2)
  8. print(val3)

Output:

Python setattr() Function

Python setattr() function is used to set a value to the object’s attribute. It takes three arguments, i.e., an object, a string, and an arbitrary value, and returns none. It is helpful when we want to add a new attribute to an object and set a value to it.

Python setattr() Function Example

  1. class Student:
  2. id = 0
  3. name = “”
  4. def __init__(self, id, name):
  5. self.id = id
  6. self.name = name
  7. student = Student(102,”Sohan”)
  8. print(student.id)
  9. print(student.name)
  10. #print(student.email) product error
  11. setattr(student, ‘email’,’sohan@abc.com’) # adding new attribute
  12. print(student.email)

Output:

Python slice() Function

Python slice() function is used to get a slice of elements from the collection of elements. Python provides two overloaded slice functions. The first function takes a single argument while the second function takes three arguments and returns a slice object. This slice object can be used to get a subsection of the collection.

Python slice() Function Example

  1. # Calling function
  2. result = slice(5) # returns slice object
  3. result2 = slice(0,5,3) # returns slice object
  4. # Displaying result
  5. print(result)
  6. print(result2)

Output:

Python sorted() Function

Python sorted() function is used to sort elements. By default, it sorts elements in an ascending order but can be sorted in descending also. It takes four arguments and returns a collection in sorted order. In the case of a dictionary, it sorts only keys, not values.

Python sorted() Function Example

  1. str = “javatpoint” # declaring string
  2. # Calling function
  3. sorted1 = sorted(str) # sorting string
  4. # Displaying result
  5. print(sorted1)

Output:

Python next() Function

Python next() function is used to fetch next item from the collection. It takes two arguments, i.e., an iterator and a default value, and returns an element.

This method calls on iterator and throws an error if no item is present. To avoid the error, we can set a default value.

Python next() Function Example

  1. number = iter([256, 32, 82]) # Creating iterator
  2. # Calling function
  3. item = next(number)
  4. # Displaying result
  5. print(item)
  6. # second item
  7. item = next(number)
  8. print(item)
  9. # third item
  10. item = next(number)
  11. print(item)

Output:

Python input() Function

Python input() function is used to get an input from the user. It prompts for the user input and reads a line. After reading data, it converts it into a string and returns it. It throws an error EOFError if EOF is read.

Python input() Function Example

  1. # Calling function
  2. val = input(“Enter a value: “)
  3. # Displaying result
  4. print(“You entered:”,val)

Output:

Python int() Function

Python int() function is used to get an integer value. It returns an expression converted into an integer number. If the argument is a floating-point, the conversion truncates the number. If the argument is outside the integer range, then it converts the number into a long type.

If the number is not a number or if a base is given, the number must be a string.

Python int() Function Example

  1. # Calling function
  2. val = int(10) # integer value
  3. val2 = int(10.52) # float value
  4. val3 = int(‘10’) # string value
  5. # Displaying result
  6. print(“integer values :”,val, val2, val3)

Output:

Python isinstance() Function

Python isinstance() function is used to check whether the given object is an instance of that class. If the object belongs to the class, it returns true. Otherwise returns False. It also returns true if the class is a subclass.

The isinstance() function takes two arguments, i.e., object and classinfo, and then it returns either True or False.

Python isinstance() function Example

  1. class Student:
  2. id = 101
  3. name = “John”
  4. def __init__(self, id, name):
  5. self.id=id
  6. self.name=name
  7. student = Student(1010,”John”)
  8. lst = [12,34,5,6,767]
  9. # Calling function
  10. print(isinstance(student, Student)) # isinstance of Student class
  11. print(isinstance(lst, Student))

Output:

Python oct() Function

Python oct() function is used to get an octal value of an integer number. This method takes an argument and returns an integer converted into an octal string. It throws an error TypeError, if argument type is other than an integer.

Python oct() function Example

  1. # Calling function
  2. val = oct(10)
  3. # Displaying result
  4. print(“Octal value of 10:”,val)

Output:

Python ord() Function

The python ord() function returns an integer representing Unicode code point for the given Unicode character.

Python ord() function Example

  1. # Code point of an integer
  2. print(ord(‘8’))
  3. # Code point of an alphabet
  4. print(ord(‘R’))
  5. # Code point of a character
  6. print(ord(‘&’))

Output:

Python pow() Function

The python pow() function is used to compute the power of a number. It 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. (x, y) % z.

Python pow() function Example

  1. # positive x, positive y (x**y)
  2. print(pow(4, 2))
  3. # negative x, positive y
  4. print(pow(-4, 2))
  5. # positive x, negative y (x**-y)
  6. print(pow(4, -2))
  7. # negative x, negative y
  8. print(pow(-4, -2))

Output:

Python print() Function

The python print() function prints the given object to the screen or other standard output devices.

Python print() function Example

  1. print(“Python is programming language.”)
  2. x = 7
  3. # Two objects passed
  4. print(“x =”, x)
  5. y = x
  6. # Three objects passed
  7. print(‘x =’, x, ‘= y’)

Output:

Python range() Function

The python range() function returns an immutable sequence of numbers starting from 0 by default, increments by 1 (by default) and ends at a specified number.

Python range() function Example

  1. # empty range
  2. print(list(range(0)))
  3. # using the range(stop)
  4. print(list(range(4)))
  5. # using the range(start, stop)
  6. print(list(range(1,7 )))

Output:

Python reversed() Function

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

Python reversed() function Example

  1. # for string
  2. String = ‘Java’
  3. print(list(reversed(String)))
  4. # for tuple
  5. Tuple = (‘J’, ‘a’, ‘v’, ‘a’)
  6. print(list(reversed(Tuple)))
  7. # for range
  8. Range = range(8, 12)
  9. print(list(reversed(Range)))
  10. # for list
  11. List = [1, 2, 7, 5]
  12. print(list(reversed(List)))

Output:

Python round() Function

The python round() function rounds off the digits of a number and returns the floating point number.

Python round() Function Example

  1. # for integers
  2. print(round(10))
  3. # for floating point
  4. print(round(10.8))
  5. # even choice
  6. print(round(6.6))

Output:

Python issubclass() Function

The python issubclass() function returns true if object argument(first argument) is a subclass of second class(second argument).

Python issubclass() Function Example

  1. class Rectangle:
  2. def __init__(rectangleType):
  3. print(‘Rectangle is a ‘, rectangleType)
  4. class Square(Rectangle):
  5. def __init__(self):
  6. Rectangle.__init__(‘square’)
  7. print(issubclass(Square, Rectangle))
  8. print(issubclass(Square, list))
  9. print(issubclass(Square, (list, Rectangle)))
  10. print(issubclass(Rectangle, (list, Rectangle)))

Output:

Python str

The python str() converts a specified value into a string.

Python str() Function Example

  1. str(‘4’)

Output:

Python tuple() Function

The python tuple() function is used to create a tuple object.

Python tuple() Function Example

  1. t1 = tuple()
  2. print(‘t1=’, t1)
  3. # creating a tuple from a list
  4. t2 = tuple([1, 6, 9])
  5. print(‘t2=’, t2)
  6. # creating a tuple from a string
  7. t1 = tuple(‘Java’)
  8. print(‘t1=’,t1)
  9. # creating a tuple from a dictionary
  10. t1 = tuple(<4: ‘four’, 5: ‘five’>)
  11. print(‘t1=’,t1)

Output:

Python type()

The python type() returns the type of the specified object if a single argument is passed to the type() built in function. If three arguments are passed, then it returns a new type object.

Python type() Function Example

  1. List = [4, 5]
  2. print(type(List))
  3. Dict =
  4. print(type(Dict))
  5. class Python:
  6. a = 0
  7. InstanceOfPython = Python()
  8. print(type(InstanceOfPython))

Output:

Python vars() function

The python vars() function returns the __dict__ attribute of the given object.

Python vars() Function Example

  1. class Python:
  2. def __init__(self, x = 7, y = 9):
  3. self.x = x
  4. self.y = y
  5. InstanceOfPython = Python()
  6. print(vars(InstanceOfPython))

Output:

Python zip() Function

The python zip() Function returns a zip object, which maps a similar index of multiple containers. It takes iterables (can be zero or more), makes it an iterator that aggregates the elements based on iterables passed, and returns an iterator of tuples.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *