Home >Backend Development >Python Tutorial >How do you sum the elements in a list of integers using Python?

How do you sum the elements in a list of integers using Python?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-28 04:53:021091browse

How do you sum the elements in a list of integers using Python?

Adding Integers in Lists with Python

Imagine a scenario where you have a list of integers, like [2, 4, 7, 12, 3]. To determine their combined value (28), you need to sum all their individual values. Here's how you can do it using Python:

<code class="python"># Method 1: Using sum() function
x = [2, 4, 7, 12, 3]
sum_of_all_numbers = sum(x)</code>

The sum() function iterates over the list, aggregating all the integer values to provide the final sum.

Alternatively, you can employ a powerful Python function called reduce() to perform this summation:

<code class="python"># Method 2: Using reduce() with lambda function
x = [2, 4, 7, 12, 3]
sum_of_all_numbers = reduce(lambda q, p: p + q, x)</code>

The reduce() function cumulatively executes a specified function on each element in the list. In this case, we use a lambda function that adds two arguments (p and q) to perform the summation. This lambda function obviates the need to define a separate function for adding integers.

The above is the detailed content of How do you sum the elements in a list of integers using Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn