Practice Questions for List Tuple Set and Dictionary and Functions
Practice Questions for List Tuple Set and Dictionary and Functions
1. Create a list of numbers from 1 to 10, then remove the number 5 from
the list.
n1 = list(range(1, 11))
n1.remove(5)
print(numbers)
8. Create a set with the elements 1, 2, 3, 4. Add the element 5 to the set.
s1 = {1, 2, 3, 4}
s1.add(5)
print(s1) # {1, 2, 3, 4, 5}
20.How do you create a dictionary with keys from a list and values set to a
default value?
keys = ['name', 'age', 'city']
default_value = None
my_dict = dict.fromkeys(keys, default_value)
print(my_dict) # {'name': None, 'age': None, 'city': None}
21.How do you create a dictionary with keys from a list and values set to a
default value?
keys = ['name', 'age', 'city']
default_value = None
my_dict = dict.fromkeys(keys, default_value)
print(my_dict) # {'name': None, 'age': None, 'city': None}
numbers = [1, 2, 3, 4, 5]
rotated_list = rotate_list(numbers, 2)
print(rotated_list) # [4, 5, 1, 2, 3]
24.Write a program to find all pairs of integers in a list whose sum is equal
to a given number.
def find_pairs(lst, target_sum):
pairs = []
seen = set()
for num in lst:
diff = target_sum - num
if diff in seen:
pairs.append((diff, num))
seen.add(num)
return pairs
25.Write a Python program to remove all duplicate values from a list while
maintaining the order.
def remove_duplicates(lst):
seen = set()
result = []
for item in lst:
if item not in seen:
result.append(item)
seen.add(item)
return result
numbers = [1, 2, 2, 3, 4, 4, 5, 1, 6]
unique_numbers = remove_duplicates(numbers)
print(unique_numbers) # [1, 2, 3, 4, 5, 6]
35.Write a Python program to split a list into evenly sized chunks of size n.
def chunk_list(lst, n):
return [lst[i:i + n] for i in range(0, len(lst), n)]
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
chunks = chunk_list(numbers, 3)
print(chunks) # [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
36.Write a Python program to count the number of unique elements in a
list.
numbers = [1, 2, 2, 3, 4, 4, 5, 6]
unique_count = len(set(numbers))
print(unique_count) #6
43.Write a Python program to find the keys with the highest and lowest
values in a dictionary.
my_dict = {'a': 50, 'b': 20, 'c': 90, 'd': 30}
max_key = max(my_dict, key=my_dict.get)
min_key = min(my_dict, key=my_dict.get)
print(f"Max key: {max_key}, Min key: {min_key}") # Max key: c, Min key: b
age = 20
if age >= 18:
print("You are eligible to vote.")
else:
print("You are not eligible to vote.")
2. if-elif-else Statement
score = 85
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
else:
print("Grade: D")
3. Nested if Statement
num = 15
if num > 10:
print("Number is greater than 10")
if num % 2 == 0:
print("It is an even number")
else:
print("It is an odd number")
else:
print("Number is 10 or less")
for i in range(5):
print(i)
if is_prime:
print(f"{num} is a prime number.")
else:
print(f"{num} is not a prime number.")
Using continue in a for Loop
count = 0
while count < 3:
print(count)
count += 1
More examples:
if num % 2 == 0:
if num % 3 == 0:
print(f"{num} is divisible by both 2 and 3")
else:
print(f"{num} is divisible by 2 but not by 3")
else:
if num % 3 == 0:
print(f"{num} is divisible by 3 but not by 2")
else:
print(f"{num} is neither divisible by 2 nor by 3")
if not found:
print(f"{target_name} not found in the list.")
if choice == 1:
print(f"Your balance is: ${balance}")
elif choice == 2:
deposit = float(input("Enter amount to deposit: "))
balance += deposit
print(f"Your new balance is: ${balance}")
elif choice == 3:
withdraw = float(input("Enter amount to withdraw: "))
if withdraw > balance:
print("Insufficient funds!")
else:
balance -= withdraw
print(f"Your new balance is: ${balance}")
elif choice == 4:
print("Thank you for using the ATM!")
break
else:
print("Invalid choice. Please try again.")
break
else:
attempts -= 1
print(f"Incorrect PIN. You have {attempts} attempts left.")
else:
print("Your account is locked due to too many failed attempts.")
Functions:
1. Pure Functions
A pure function is a function that always produces the same output for the
same input and does not have side effects.
# Pure function that takes a list and returns a new list with elements doubled
def double_list_elements(lst):
return [x * 2 for x in lst]
# Pure function that converts a list of numbers to strings and joins them with a
separator
def join_numbers(numbers, separator=", "):
return separator.join(str(num) for num in numbers)
4. Higher-Order Functions
A higher-order function is a function that takes other functions as arguments or
returns a function as its result.
Example with map()
The map() function applies a given function to all items in an iterable.
5. List Comprehensions
List comprehensions provide a concise way to create lists based on existing
lists. They are often used as a more readable alternative to map() and filter().
6. Recursion
Recursion is a technique in functional programming where a function calls itself
to solve a problem.
result = factorial(5)
print(result) # Output: 120