-
How do you describe this for loop?
words = ["apple", "banana", "carrot", "durian"] word_lengths = [] for word in words: word_lengths.append(len(word)) print(word_lengths) # [5, 6, 6, 6]
-
What will be the output of this for loop?
values = [10, "Hello", 3.14, True, [1, 2, 3], {"name": "John"}] for value in values: value_type = type(value) print(f"The type of {value} is {value_type}.")
-
How do you describe this code?
values = [10, "Hello", 3.14, True, [1, 2, 3], {"name": "John"}] types = [type(value) for value in values] print(types)
-
Complete the list comprehension that converts the values inside the strings list to float numbers.
strings = ["10", "3.14", "5", "7.5", "2.8"] numbers = [''(string) for string in strings] print(numbers) # [10.0, 3.14, 5.0, 7.5, 2.8]
-
Use list comprehension to filter students with grade A.
students = [ {"name": "John", "age": 18, "grade": "A"}, {"name": "Emily", "age": 17, "grade": "B"}, {"name": "Michael", "age": 19, "grade": "A"}, {"name": "Sophia", "age": 18, "grade": "B"}, ] grade_a_students = [student for student in students if '' ] print(grade_a_students)
-
Use list comprehension to filter employees from the HR department.
employees = [ {"name": "John", "department": "HR", "salary": 5000}, {"name": "Emily", "department": "Finance", "salary": 6000}, {"name": "Michael", "department": "IT", "salary": 5500}, {"name": "Sophia", "department": "HR", "salary": 5200}, ] hr_employees = [employee for employee in employees if ''] print(hr_employees)
-
Use list comprehension to filter completed tasks (True for the “completed” key).
tasks = [ {"name": "Task 1", "completed": True}, {"name": "Task 2", "completed": False}, {"name": "Task 3", "completed": True}, {"name": "Task 4", "completed": False}, ] completed_tasks = [task for task in tasks if ''["completed"]] print(completed_tasks)
Python Exercises for Comprehension
If you’ve faced difficulties with these exercises, take a look at Comprehension Module on my Python course.
You can also share ‘Python Comprehension’ Exercises on your:
X (Twitter) – Telegram – Linkedin – Facebook – or on your favorite platform…