0% found this document useful (0 votes)
20 views7 pages

Python Practice Questions

The document contains Python programs for various tasks including calculating the sum of elements in a list, finding maximum and minimum values, counting even and odd numbers, searching for a specific value, transposing a matrix, finding common elements in two lists, checking if a list is sorted, generating combinations from two lists, removing duplicates while preserving order, and computing cumulative sums. Each task is demonstrated with example code snippets. The programs utilize basic Python constructs such as loops, conditionals, and functions.

Uploaded by

Sreya 369
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views7 pages

Python Practice Questions

The document contains Python programs for various tasks including calculating the sum of elements in a list, finding maximum and minimum values, counting even and odd numbers, searching for a specific value, transposing a matrix, finding common elements in two lists, checking if a list is sorted, generating combinations from two lists, removing duplicates while preserving order, and computing cumulative sums. Each task is demonstrated with example code snippets. The programs utilize basic Python constructs such as loops, conditionals, and functions.

Uploaded by

Sreya 369
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

1.Calculate the sum of all elements in a list.

Given a list of numbers, write a Python program to calculate the sum of all elements in the list.

# Given list of numbers


numbers = [1, 2, 3, 4, 5]

# Initialize total sum to 0


total = 0

# Iterate through each element in the list


for num in numbers:
# Add each element to the total sum
total += num

# Print the sum of all elements in the list


print("Sum of elements in the list:", total)

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.

# Given list of numbers


numbers = [5, 2, 7, 1, 9, 3]

# Find maximum and minimum values


max_value = max(numbers)
min_value = min(numbers)

# Print maximum and minimum values


print("Maximum value:", max_value)
print("Minimum value:", min_value)
-----------------------------------------------------------------------------------------------------------------------------
# Given list of numbers
numbers = [5, 2, 7, 1, 9, 3]

# Initialize variables to store maximum and minimum values


max_value = numbers[0] # Assume first element as maximum initially
min_value = numbers[0] # Assume first element as minimum initially

# Iterate through each element in the list


for num in numbers:
# Update maximum value if current element is greater
if num > max_value:
max_value = num

# Update minimum value if current element is smaller


if num < min_value:
min_value = num

# Print maximum and minimum values


print("Maximum value:", max_value)
print("Minimum value:", min_value)

3.Count the number of even and odd numbers in a list.


Given a list of integers, write a Python program to count the number of even and odd numbers in
the list separately.

# Given list of numbers


numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Initialize counters for even and odd numbers


even_count = 0
odd_count = 0

# Iterate through each element in the list


for num in numbers:
# Check if the number is even
if num % 2 == 0:
even_count += 1
else:
odd_count += 1

# Print the counts of even and odd numbers


print("Number of even numbers:", even_count)
print("Number of odd numbers:", odd_count)
---------------------------------------------------------------------------------------------------------------------------------------
4.Search for a specific value in a list.
Write a Python program that takes a value as input and checks if it exists in a given list. If found,
print its index; otherwise, print a message indicating that the value is not in the list.

# Given list of numbers


numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Take input for the value to search


value = int(input("Enter the value to search: "))

# Initialize a variable to store the index of the value (if found)


index = None

# Iterate through each element in the list


for i, num in enumerate(numbers):
# Check if the current element matches the value
if num == value:
index = i # Store the index of the value
break # Exit the loop if value is found
# Check if the value was found and print the result
if index is not None:
print("Value", value, "found at index:", index)
else:
print("Value", value, "is not in the list.")
----------------------------------------------------------------------------------------------------------------------------------
5.Transpose a matrix represented as a list of lists.
Given a matrix represented as a list of lists, write a Python program to transpose the matrix (i.e.,
convert rows into columns and columns into rows).

# Given matrix represented as a list of lists


matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]

# Transpose the matrix


transposed_matrix = [[row[i] for row in matrix] for i in range(len(matrix[0]))]

# Print the original matrix


print("Original Matrix:")
for row in matrix:
print(row)

# Print the transposed matrix


print("\nTransposed Matrix:")
for row in transposed_matrix:
print(row)
# Given matrix represented as a list of lists
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]

# Transpose the matrix


transposed_matrix = [[row[i] for row in matrix] for i in range(len(matrix[0]))]

# Print the transposed matrix


for row in transposed_matrix:
print(row)
---------------------------------------------------------------------------------------------------------------------------------------

6.Find common elements in two lists.


Write a Python program that takes two lists as input and returns a new list containing common
elements found in both lists.

# Given two lists


list1 = [1, 2, 3, 4, 5]
list2 = [3, 4, 5, 6, 7]

# Find common elements


common_elements = set(list1) & set(list2)

# Print the common elements


print("Common elements:", list(common_elements))
---------------------------------------------------------------------------------------------------------------------------------------
def find_common_elements(list1, list2):
# Convert lists to sets to remove duplicates
set1 = set(list1)
set2 = set(list2)
# Find common elements using set intersection
common_elements = set1.intersection(set2)
# Convert set back to list
return list(common_elements)

# Example lists
list1 = [1, 2, 3, 4, 5]
list2 = [3, 4, 5, 6, 7]

# Find common elements


common_elements = find_common_elements(list1, list2)

# Print the common elements


print("Common elements:", common_elements)
---------------------------------------------------------------------------------------------------------------------------------------
7.Check if a list is sorted in ascending order.
Write a Python program that checks whether a given list of numbers is sorted in ascending order or
not.

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]

# Check if the list is sorted in ascending order


sorted_status = is_sorted_ascending(my_list)

# Print the result


if sorted_status:
print("The list is sorted in ascending order.")
else:
print("The list is not sorted in ascending order.")
---------------------------------------------------------------------------------------------------------------------------------------

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]

# Check if the list is sorted in ascending order


if is_sorted_ascending(numbers):
print("The list is sorted in ascending order.")
else:
print("The list is not sorted in ascending order.")
-------------------------------------------------------------------------------------------------------------------------------

8.Generate all possible combinations from two lists.


Write a Python program that generates all possible combinations of elements from two given lists.

# Given two lists


list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']

# Initialize an empty list to store combinations


combinations = []

# Generate combinations using nested loops


for num in list1:
for letter in list2:
combinations.append((num, letter))

# Print all possible combinations


print("All possible combinations:")
for combination in combinations:
print(combination)

from itertools import product

# Given two lists


list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']

# Generate all possible combinations


combinations = list(product(list1, list2))

# Print all possible combinations


print("All possible combinations:")
for combination in combinations:
print(combination)
---------------------------------------------------------------------------------------------------------------------------------------
9.Remove duplicate elements from a list.
Write a Python program to remove duplicate elements from a list while preserving the order of
elements.

# Given list with duplicate elements


my_list = [1, 2, 3, 1, 2, 4, 5, 3]

# Remove duplicate elements


unique_list = list(set(my_list))

# Print the unique list


print("List with duplicates removed:", unique_list)
-------------------------------------------------------------------------------------------------------------------------------------
# Given list with duplicate elements
my_list = [1, 2, 3, 1, 2, 4, 5, 3]

# Initialize an empty set to keep track of unique elements


unique_elements = set()

# Initialize an empty list to store the unique elements in order


unique_list = []

# Iterate through the original list


for element in my_list:
# Check if the element is not already in the set
if element not in unique_elements:
# Add the element to the set (to mark it as seen)
unique_elements.add(element)
# Add the element to the unique list
unique_list.append(element)

# 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.

# Given list of numbers


numbers = [1, 2, 3, 4, 5]

# Initialize a variable to store the cumulative sum


cumulative_sum = 0

# Initialize an empty list to store the cumulative sums


cumulative_sums = []

# Iterate through each element in the list


for num in numbers:
# Add the current element to the cumulative sum
cumulative_sum += num
# Append the cumulative sum to the list of cumulative sums
cumulative_sums.append(cumulative_sum)

# Print the cumulative sums


print("Cumulative sums:", cumulative_sums)
# Given list of numbers
numbers = [1, 2, 3, 4, 5]

# Initialize a variable to store the cumulative sum


cumulative_sum = 0

# Initialize an empty list to store the cumulative sums


cumulative_sums = []
# Iterate through each element in the list
for num in numbers:
# Add the current element to the cumulative sum
cumulative_sum += num
# Append the cumulative sum to the list of cumulative sums
cumulative_sums.append(cumulative_sum)

# Print the cumulative sums


print("Cumulative sums:", cumulative_sums)

You might also like