Dada una lista de números, escriba un programa en Python para encontrar la suma de todos los elementos de la lista.
Ejemplo:
Input: [12, 15, 3, 10] Output: 40 Input: [17, 5, 3, 5] Output: 30
Ejemplo 1:
Python3
# Python program to find sum of elements in list total = 0 # creating a list list1 = [11, 5, 17, 18, 23] # Iterate each element in list # and add them in variable total for ele in range(0, len(list1)): total = total + list1[ele] # printing total value print("Sum of all elements in given list: ", total)
Producción:
Sum of all elements in given list: 74
Ejemplo #2: Usar el ciclo while()
Python3
# Python program to find sum of elements in list total = 0 ele = 0 # creating a list list1 = [11, 5, 17, 18, 23] # Iterate each element in list # and add them in variable total while(ele < len(list1)): total = total + list1[ele] ele += 1 # printing total value print("Sum of all elements in given list: ", total)
Producción:
Sum of all elements in given list: 74
Ejemplo #3: Manera recursiva
Python3
# Python program to find sum of all # elements in list using recursion # creating a list list1 = [11, 5, 17, 18, 23] # creating sum_list function def sumOfList(list, size): if (size == 0): return 0 else: return list[size - 1] + sumOfList(list, size - 1) # Driver code total = sumOfList(list1, len(list1)) print("Sum of all elements in given list: ", total)
Producción:
Sum of all elements in given list: 74
Ejemplo #4: Usando el método sum()
Python3
# Python program to find sum of elements in list # creating a list list1 = [11, 5, 17, 18, 23] # using sum() function total = sum(list1) # printing total value print("Sum of all elements in given list: ", total)
Producción:
Sum of all elements in given list: 74
Ejemplo 5: Uso de la función add() del módulo de operador.
Primero tenemos que importar el módulo del operador y luego usar la función add() del módulo del operador agregando todos los valores en la lista.
Python3
# Python 3 program to find the sum of all elements in the # list using add function of operator module from operator import* list1 = [12, 15, 3, 10] result = 0 for i in list1: # Adding elements in the list using # add function of operator module result = add(i, 0)+result # printing the result print(result)
Producción
40