Practice questions and answers for list, tuple, set, and dictionary
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)
2. Write a program to find the second largest number in a list.
n2 = [3, 8, 1, 5, 10, 6]
n2.sort()
second_largest = n2[-2]
print(second_largest)
3. How can you check if an element exists in a list?
colors = ['red', 'blue', 'green']
print('red' in colors) # True
print('yellow' in colors) # False
4. Create a tuple containing numbers from 1 to 5. Can you modify one of
the elements in the tuple?
t1 = (1, 2, 3, 4, 5)
# Tuples are immutable, so you cannot modify them
# t1[1] = 10 # This will raise a TypeError
5. How do you access the last element of a tuple?
t3 = (10, 20, 30, 40)
last_element = t3[-1]
print(last_element) # 40
6. What is tuple unpacking? Demonstrate with an example.
t4 = (4, 5)
x, y = t4
print(f"x: {x}, y: {y}") # x: 4, y: 5
7. Write a program to merge two tuples.
t5 = (1, 2, 3)
t6 = (4, 5, 6)
mt = t1 + t2
print(mt) # (1, 2, 3, 4, 5, 6)
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}
9. Remove duplicates from a list using a set.
m1 = [1, 2, 2, 3, 4, 4, 5]
m2 = list(set(m1))
print(m2) # [1, 2, 3, 4, 5]
10.Create a dictionary with the following key-value pairs: {"name": "Preeti",
"age": 25, "city": "Pune"}
d1 = {"name": "Preeti", "age": 25, "city": "Pune"}
print(d1)
## How do you access the value associated with the key "age" in the
dictionary above?
age = d1["age"]
print(age) # 25
## Add a new key-value pair "job": "Developer" to the dictionary.
d1["job"] = "Developer"
print(d1)
## Write a program to iterate over all keys and values in a dictionary.
for key, value in d1.items():
print(f"{key}: {value}")
## How can you check if a key exists in a dictionary?
print("name" in d1) # True
print("salary" in d1) # False
11.Write a Python program to reverse a list without using the reverse()
method.
p1 = [1, 2, 3, 4, 5]
reversed_numbers = p1[::-1]
print(reversed_numbers) # [5, 4, 3, 2, 1]
12.Write a program to find the index of an element in a list.
fruits = ['apple', 'banana', 'cherry', 'date']
index = fruits.index('cherry')
print(index) #2
13.How do you sort a list of tuples based on the second element of each
tuple?
tuples_list = [(1, 'apple'), (3, 'banana'), (2, 'cherry')]
sorted_list = sorted(tuples_list, key = lambda x: x[1])
print(sorted_list) # [(1, 'apple'), (3, 'banana'), (2, 'cherry')]
14.Write a program to flatten a nested list.
nested_list = [[1, 2], [3, 4], [5, 6]]
flat_list = [item for sublist in nested_list for item in sublist]
print(flat_list) # [1, 2, 3, 4, 5, 6]
15.Convert a list to a tuple and then back to a list.
l1 = [1, 2, 3, 4, 5]
t1 = tuple(l1)
new_list = list(t1)
print(t1) # (1, 2, 3, 4, 5)
print(new_list) # [1, 2, 3, 4, 5]
16.Write a program to create a tuple of numbers from 1 to 10 and then
slice it to extract the first five elements.
numbers = tuple(range(1, 11))
first_five = numbers[:5]
print(first_five) # (1, 2, 3, 4, 5)
17.Write a program to merge two dictionaries.
dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}
merged_dict = {**dict1, **dict2}
print(merged_dict) # {'a': 1, 'b': 2, 'c': 3, 'd': 4}
18.How do you iterate through all the keys in a dictionary?
my_dict = {'name': 'Priya', 'age': 30, 'city': 'Pune'}
for key in my_dict:
print(key)
19.Write a program to count the frequency of each element in a list using
a dictionary.
numbers = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
frequency = {}
for num in numbers:
frequency[num] = frequency.get(num, 0) + 1
print(frequency) # {1: 1, 2: 2, 3: 3, 4: 4}
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}
22.Write a program to sort a dictionary by its values.
my_dict = {'apple': 5, 'banana': 2, 'cherry': 8}
sorted_dict = dict(sorted(my_dict.items(), key=lambda item: item[1]))
print(sorted_dict) # {'banana': 2, 'apple': 5, 'cherry': 8}
23.Write a Python program to rotate a list by k positions to the right.
def rotate_list(lst, k):
k = k % len(lst) # Handle cases where k > len(lst)
return lst[-k:] + lst[:-k]
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
numbers = [2, 4, 3, 5, 7, 8, -1]
target = 7
result = find_pairs(numbers, target)
print(result) # [(4, 3), (5, 2), (8, -1)]
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]
26.Write a Python program to find the maximum and minimum values in a
tuple.
my_tuple = (5, 2, 8, 1, 9, 3)
max_value = max(my_tuple)
min_value = min(my_tuple)
print(f"Max: {max_value}, Min: {min_value}") # Max: 9, Min: 1
27.Write a program to convert a tuple of strings into a single concatenated
string.
words = ('Hello', 'World', 'Python', 'Programming')
concatenated_string = ' '.join(words)
print(concatenated_string) # "Hello World Python Programming"
28.Write a Python program to create a nested tuple.
nested_tuple = ((1, 2, 3), (4, 5, 6), (7, 8, 9))
print(nested_tuple)
# ((1, 2, 3), (4, 5, 6), (7, 8, 9))
29.Write a program to invert a dictionary (swap keys and values).
my_dict = {'a': 1, 'b': 2, 'c': 3}
inverted_dict = {value: key for key, value in my_dict.items()}
print(inverted_dict) # {1: 'a', 2: 'b', 3: 'c'}
30.Write a program to sort a dictionary by its keys.
my_dict = {'banana': 2, 'apple': 5, 'cherry': 8}
sorted_dict = dict(sorted(my_dict.items()))
print(sorted_dict) # {'apple': 5, 'banana': 2, 'cherry': 8}
31.Write a Python program to find the key of the maximum value in a
dictionary.
my_dict = {'a': 15, 'b': 20, 'c': 5}
max_key = max(my_dict, key=my_dict.get)
print(max_key) # 'b'
32.Write a program to remove a key from a dictionary safely, i.e., without
raising an error if the key doesn't exist.
my_dict = {'a': 1, 'b': 2, 'c': 3}
removed_value = my_dict.pop('b', None) # Remove 'b' or return None if it
doesn't exist
print(my_dict) # {'a': 1, 'c': 3}
33.Write a Python program to find the longest word in a list of words.
words = ['apple', 'banana', 'cherry', 'pineapple', 'strawberry']
longest_word = max(words, key=len)
print(longest_word) # 'strawberry'
34.Write a Python program to remove all occurrences of a specific
element from a list.
numbers = [1, 2, 3, 2, 4, 2, 5]
value_to_remove = 2
filtered_numbers = [num for num in numbers if num != value_to_remove]
print(filtered_numbers) # [1, 3, 4, 5]
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
37.Write a program to convert a tuple of tuples into a dictionary.
tuple_data = (('a', 1), ('b', 2), ('c', 3))
dictionary = dict(tuple_data)
print(dictionary) # {'a': 1, 'b': 2, 'c': 3}
38.Write a Python program to find repeated items in a tuple.
my_tuple = (1, 2, 3, 4, 2, 5, 3, 6)
repeated_items = set([item for item in my_tuple if my_tuple.count(item) >
1])
print(repeated_items) # {2, 3}
39.Write a Python program to get the average of unique numbers in a list
using a set.
numbers = [1, 2, 2, 3, 4, 4, 5]
unique_numbers = set(numbers)
average = sum(unique_numbers) / len(unique_numbers)
print(average) # 3.0
40.Write a Python program to count the occurrences of each character in a
string using a dictionary.
text = "hello world"
char_count = {}
for char in text:
char_count[char] = char_count.get(char, 0) + 1
print(char_count) # {'h': 1, 'e': 1, 'l': 3, 'o': 2, ' ': 1, 'w': 1, 'r': 1, 'd': 1}
41.Write a Python program to remove duplicates in the dictionary based
on its values.
dict_with_duplicates = {'a': 1, 'b': 2, 'c': 1, 'd': 3}
unique_values = {}
for key, value in dict_with_duplicates.items():
if value not in unique_values.values():
unique_values[key] = value
print(unique_values) # {'a': 1, 'b': 2, 'd': 3}
42.Write a Python program to merge a list of dictionaries into a single
dictionary.
dict_list = [{'a': 1, 'b': 2}, {'c': 3, 'd': 4}, {'e': 5}]
merged_dict = {}
for d in dict_list:
merged_dict.update(d)
print(merged_dict) # {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
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
44.Write a Python program to sort a dictionary by values in descending
order.
my_dict = {'apple': 10, 'banana': 5, 'cherry': 20}
sorted_dict = dict(sorted(my_dict.items(), key=lambda item: item[1],
reverse=True))
print(sorted_dict) # {'cherry': 20, 'apple': 10, 'banana': 5}
Examples of if-else Statements
1. Basic if-else Statement
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")
Combining Multiple Conditions with Logical Operators
temperature = 25
humidity = 80
if temperature > 20 and humidity > 70:
print("It's warm and humid outside.")
elif temperature > 20 and humidity <= 70:
print("It's warm but not humid.")
else:
print("It's either cool or moderate outside.")
Using the or Operator in Conditions
day = "Saturday"
weather = "rainy"
if day == "Saturday" or day == "Sunday":
print("It's the weekend!")
else:
print("It's a weekday.")
Ternary Operator (Conditional Expression)
age = 17
status = "Adult" if age >= 18 else "Minor"
print(status)
Examples of for Loops
1. Simple for Loop
for i in range(5):
print(i)
2. Iterating Through a List
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
3. Using break in a for Loop
for num in range(5):
if num == 3:
break
print(num)
Looping Through a Dictionary
student_grades = {"Alice": 85, "Bob": 90, "Charlie": 78}
for student, grade in student_grades.items():
print(f"{student} has a grade of {grade}")
Using a for Loop with else
for i in range(5):
print(i)
else:
print("The loop completed successfully.")
Finding Prime Numbers Using a for Loop
num = 29
is_prime = True
for i in range(2, num):
if num % i == 0:
is_prime = False
break
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
for num in range(5):
if num == 2:
continue
print(num)
Examples of while Loops
1. Basic while Loop
count = 0
while count < 3:
print(count)
count += 1
Using break in a while Loop
i=1
while i <= 5:
if i == 4:
break
print(i)
i += 1
Using continue in a while Loop
i=0
while i < 5:
i += 1
if i == 3:
continue
print(i)
Infinite Loop Example
while True:
print("This is an infinite loop")
break
Counting Down with a while Loop
count = 5
while count > 0:
print(count)
count -= 1
print("Countdown complete!")
while Loop with User Input
while True:
answer = input("Type 'exit' to quit: ")
if answer.lower() == 'exit':
print("Exiting the loop...")
break
else:
print("You entered:", answer)
Nested while Loops
i=1
while i <= 3:
j=1
while j <= 2:
print(f"i = {i}, j = {j}")
j += 1
i += 1
More examples:
Using if-else with Loops to Categorize Numbers
numbers = [12, 37, 5, 42, 8, 3]
even_numbers = []
odd_numbers = []
for num in numbers:
if num % 2 == 0:
even_numbers.append(num)
else:
odd_numbers.append(num)
print("Even numbers:", even_numbers)
print("Odd numbers:", odd_numbers)
Multiple Conditions with Nested if-else Statements
num = 48
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")
Using if-else with List Comprehensions
numbers = [10, 15, 22, 33, 40]
even_or_odd = ["Even" if num % 2 == 0 else "Odd" for num in numbers]
print(even_or_odd)
Searching for an Element in a List Using a for Loop
names = ["Alice", "Bob", "Charlie", "Diana"]
target_name = "Charlie"
found = False
for name in names:
if name == target_name:
print(f"{target_name} found in the list!")
found = True
break
if not found:
print(f"{target_name} not found in the list.")
Pattern Generation Using Nested Loops
rows = 5
for i in range(1, rows + 1):
for j in range(1, i + 1):
print("*", end=" ")
print() # Move to the next line after each row
Finding Prime Numbers in a Range Using a Nested for Loop
lower = 10
upper = 20
for num in range(lower, upper + 1):
is_prime = True
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
is_prime = False
break
if is_prime:
print(f"{num} is a prime number")
Fibonacci Sequence Using a while Loop
n_terms = 10
n1, n2 = 0, 1
count = 0
while count < n_terms:
print(n1, end=" ")
nth = n1 + n2
n1 = n2
n2 = nth
count += 1
Using for-else to Check for the Absence of a Condition
numbers = [1, 2, 3, 4, 5]
target = 6
for num in numbers:
if num == target:
print(f"{target} found in the list.")
break
else:
print(f"{target} not found in the list.")
Real-World Example: Simulating a Simple ATM System
balance = 1000 # Initial balance
attempts = 3
while attempts > 0:
pin = int(input("Enter your PIN: "))
if pin == 1234:
print("Access granted.")
while True:
print("\n1. Check Balance\n2. Deposit\n3. Withdraw\n4. Exit")
choice = int(input("Enter your choice: "))
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 Example
def add(x, y):
return x + y
result = add(3, 5) # Output will always be 8
print(result) # Output: 8
Example 1: Calculating the Square of a Number
# Pure function to calculate the square of a number
def square(num):
return num * num
# Calling the function
print(square(4)) # Output: 16
print(square(4)) # Output: 16 (always returns the same result)
Example 2: Summing Two Numbers
# Pure function to add two numbers
def add_numbers(a, b):
return a + b
# Calling the function
print(add_numbers(3, 5)) # Output: 8
print(add_numbers(3, 5)) # Output: 8
Example 3: Checking for Even Number
# Pure function to check if a number is even
def is_even(num):
return num % 2 == 0
# Calling the function
print(is_even(4)) # Output: True
print(is_even(7)) # Output: False
Example 4: Finding the Maximum in a List
# Pure function to find the maximum element in a list
def max_value(numbers):
return max(numbers)
# Calling the function
numbers_list = [3, 5, 1, 8, 2]
print(max_value(numbers_list)) # Output: 8
print(max_value(numbers_list)) # Output: 8
Example 5: Concatenating Two Strings
# Pure function to concatenate two strings
def concatenate(str1, str2):
return str1 + str2
# Calling the function
print(concatenate("Hello, ", "World!")) # Output: Hello, World!
print(concatenate("Hello, ", "World!")) # Output: Hello, World!
Example 6: Calculating the Factorial of a Number
# Pure function to calculate the factorial of a number
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)
# Calling the function
print(factorial(5)) # Output: 120
print(factorial(5)) # Output: 120
Example 7: Filtering Even Numbers from a List
# Pure function to filter even numbers from a list
def filter_even(numbers):
return [num for num in numbers if num % 2 == 0]
# Calling the function
numbers_list = [1, 2, 3, 4, 5, 6]
print(filter_even(numbers_list)) # Output: [2, 4, 6]
print(filter_even(numbers_list)) # Output: [2, 4, 6]
Example 8: Reversing a String
# Pure function to reverse a string
def reverse_string(s):
return s[::-1]
# Calling the function
print(reverse_string("Python")) # Output: nohtyP
print(reverse_string("Python")) # Output: nohtyP
Example 9: Doubling Each Element in a List
# Pure function to double each element in a list
def double_elements(numbers):
return [num * 2 for num in numbers]
# Calling the function
numbers_list = [1, 2, 3, 4]
print(double_elements(numbers_list)) # Output: [2, 4, 6, 8]
print(double_elements(numbers_list)) # Output: [2, 4, 6, 8]
Example 10: Summing Elements in a List
# Pure function to sum elements in a list
def sum_elements(numbers):
return sum(numbers)
# Calling the function
numbers_list = [1, 2, 3, 4, 5]
print(sum_elements(numbers_list)) # Output: 15
print(sum_elements(numbers_list)) # Output: 15
Example 11: Function with Scalar Arguments
# Pure function with integer arguments
def multiply(a, b):
return a * b
# Calling the function with the same arguments
print(multiply(3, 4)) # Output: 12
print(multiply(3, 4)) # Output: 12
Example 12: Function with Tuple Arguments
# Pure function that accepts a tuple and returns a modified tuple
def add_to_tuple(tup, value):
return tup + (value,)
# Calling the function with the same arguments
tup = (1, 2, 3)
print(add_to_tuple(tup, 4)) # Output: (1, 2, 3, 4)
print(add_to_tuple(tup, 4)) # Output: (1, 2, 3, 4)
Example 13: Function with List Arguments (Returning a New List)
# 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]
# Calling the function with the same arguments
numbers = [1, 2, 3]
print(double_list_elements(numbers)) # Output: [2, 4, 6]
print(double_list_elements(numbers)) # Output: [2, 4, 6]
Example 14: Function with String Arguments
# Pure function that reverses a string
def reverse_string(s):
return s[::-1]
# Calling the function with the same arguments
print(reverse_string("hello")) # Output: "olleh"
print(reverse_string("hello")) # Output: "olleh"
Example 15: Function with Nested Data Structures (List of Tuples)
# Pure function to sum all first elements of a list of tuples
def sum_first_elements(tuples):
return sum(t[0] for t in tuples)
# Calling the function with the same arguments
data = [(1, 2), (3, 4), (5, 6)]
print(sum_first_elements(data)) # Output: 9
print(sum_first_elements(data)) # Output: 9
Example 16: Function with Dictionaries
# Pure function that returns a new dictionary with values incremented by 1
def increment_dict_values(d):
return {key: value + 1 for key, value in d.items()}
# Calling the function with the same arguments
data_dict = {'a': 1, 'b': 2, 'c': 3}
print(increment_dict_values(data_dict)) # Output: {'a': 2, 'b': 3, 'c': 4}
print(increment_dict_values(data_dict)) # Output: {'a': 2, 'b': 3, 'c': 4}
Example 17: Function with Default Arguments
# Pure function with default arguments
def greet(name="Guest"):
return f"Hello, {name}!"
# Calling the function with and without the argument
print(greet("Alice")) # Output: "Hello, Alice!"
print(greet()) # Output: "Hello, Guest!"
Example 18: Function Using Boolean Arguments
# Pure function that checks if a number is within a range
def is_in_range(number, start, end):
return start <= number <= end
# Calling the function with the same arguments
print(is_in_range(5, 1, 10)) # Output: True
print(is_in_range(12, 1, 10)) # Output: False
Example 19: Function with Floating-Point Arguments
# Pure function that returns the square root of a number
def square_root(num):
return num ** 0.5
# Calling the function with the same arguments
print(square_root(16)) # Output: 4.0
print(square_root(16)) # Output: 4.0
Example 20: Function with Multiple Data Types (Mixed Arguments)
# 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)
# Calling the function with the same arguments
numbers_list = [1, 2, 3, 4]
print(join_numbers(numbers_list, "-")) # Output: "1-2-3-4"
print(join_numbers(numbers_list, "-")) # Output: "1-2-3-4"
2. Functions as First-Class Citizens
In Python, functions are first-class citizens, meaning they can be passed around
as arguments, returned from other functions, and assigned to variables.
# Example of a function returning another function
def greet(name):
return f"Hello, {name}!"
def say_hello(func):
return func("Alice")
print(say_hello(greet)) # Output: Hello, Alice!
3. Lambda Functions (Anonymous Functions)
Lambda functions are small, anonymous functions defined using the lambda
keyword. They are often used when a function is needed temporarily.
# Lambda Function Example
multiply = lambda x, y: x * y
result = multiply(4, 5)
print(result) # Output: 20
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.
# Using map() with a lambda function
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x ** 2, numbers))
print(squared) # Output: [1, 4, 9, 16, 25]
Example with filter()
The filter() function filters elements in an iterable based on a condition.
# Using filter() with a lambda function
numbers = [10, 15, 20, 25, 30]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers) # Output: [10, 20, 30]
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().
# List comprehension to create a list of squares
numbers = [1, 2, 3, 4, 5]
squares = [x ** 2 for x in numbers]
print(squares) # Output: [1, 4, 9, 16, 25]
# List comprehension with a condition (equivalent to filter)
even_squares = [x ** 2 for x in numbers if x % 2 == 0]
print(even_squares) # Output: [4, 16]
6. Recursion
Recursion is a technique in functional programming where a function calls itself
to solve a problem.
# Recursive function to calculate factorial of a number
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n - 1)
result = factorial(5)
print(result) # Output: 120
7. Immutable Data Structures
Functional programming favors the use of immutable data structures, such as
tuples and strings, because they do not change their state.
# Immutable data structure example with a tuple
numbers = (1, 2, 3)
# numbers[0] = 5 # This will raise an error as tuples are immutable
# Instead, create a new tuple with the desired change
new_numbers = (5,) + numbers[1:]
print(new_numbers) # Output: (5, 2, 3)