इस लेख में, हम नीचे दिए गए समस्या कथन के समाधान के बारे में जानेंगे।
समस्या कथन - हमें एक सूची को पुनरावृत्त करने योग्य दिया गया है, हमें सूची के योग की गणना करने की आवश्यकता है
यहां हम 3 दृष्टिकोणों पर चर्चा करेंगे जैसा कि नीचे चर्चा की गई है
लूप के लिए उपयोग करना
उदाहरण
# sum
total = 0
# creating a list
list1 = [11, 22,33,44,55,66]
# iterating over the list
for ele in range(0, len(list1)):
total = total + list1[ele]
# printing total value
print("Sum of all elements in given list: ", total) आउटपुट
Sum of the array is 231
जबकि लूप का उपयोग करना
उदाहरण
# Python program to find sum of elements in list
total = 0
ele = 0
# creating a list
list1 = [11,22,33,44,55,66]
# iterating using loop
while(ele < len(list1)):
total = total + list1[ele]
ele += 1
# printing total value
print("Sum of all elements in given list: ", total) आउटपुट
Sum of the array is 231
फ़ंक्शन बनाकर रिकर्सन का उपयोग करना
उदाहरण
# list
list1 = [11,22,33,44,55,66]
# function following recursion
def sumOfList(list, size):
if (size == 0):
return 0
else:
return list[size - 1] + sumOfList(list, size - 1)
# main
total = sumOfList(list1, len(list1))
print("Sum of all elements in given list: ", total) आउटपुट
Sum of the array is 231
निष्कर्ष
इस लेख में, हमने सीखा है कि किसी सूची में तत्वों के योग को कैसे प्रिंट किया जाता है।