Python Practice Questions
Python Practice Questions
Given a list of numbers, write a Python program to calculate the sum of all elements in the list.
def calculate_sum(numbers):
total = 0
for num in numbers:
total += num
return total
# Example usage:
my_list = [1, 2, 3, 4, 5]
result = calculate_sum(my_list)
print("Sum of elements in the list:", result)
my_list = [1, 2, 3, 4, 5]
result = sum(my_list)
print("Sum of elements in the list:", result)
---------------------------------------------------------------------------------------------------------------------------------------
2.Find the maximum and minimum values in a list.
Write a Python program to find the maximum and minimum values in a given list of numbers.
# Example lists
list1 = [1, 2, 3, 4, 5]
list2 = [3, 4, 5, 6, 7]
def is_sorted_ascending(lst):
# Iterate through the list starting from the second element
for i in range(1, len(lst)):
# Check if the current element is less than the previous one
if lst[i] < lst[i - 1]:
return False
# If no elements were found out of order, return True
return True
# Example list
my_list = [1, 2, 3, 4, 5]
def is_sorted_ascending(lst):
# Iterate through the list starting from the second element
for i in range(1, len(lst)):
# Check if the current element is less than the previous one
if lst[i] < lst[i - 1]:
return False
# If no elements were found out of order, return True
return True
# Example list
numbers = [1, 2, 3, 4, 5]
# Print the list with duplicate elements removed while preserving the order
print("List with duplicates removed while preserving order:", unique_list)
---------------------------------------------------------------------------------------------------------------------------------------
10.Compute the cumulative sum of elements in a list.
Given a list of numbers, write a Python program to compute the cumulative sum of elements,
where each element at index i contains the sum of all elements from index 0 to i in the original list.