Python List, Set and Dict Comprehensions

List Comprehensions

List comprehension examples: https://youtube.com/shorts/cnSLqqx_huQ?si=5J19IZzT23VvtDmp

Dict Comprehension

Dictionary comprehensions are a powerful and concise way to create dictionaries in Python.

Syntax:

{key_expression: value_expression for item in iterable if condition}

Key Terms

True/False (Mark T for True and F for False)

Answer Key (True/False):

Multiple Choice (Select the best answer)

  1. Which function would you use to determine the type of a variable in Python?
    • A) id()
    • B) type()
    • C) str()
    • D) isinstance()

#28 What is a list comprehension in Python?

Watch the Video Tutorial for the Answer: https://youtu.be/1fVckZom4K0

#python #pythonpoll #MCQsTest #yasirbhutta

a. A way to create a list using a for loop and if conditions b. A way to create a list using a while loop and if conditions c. A way to create a dictionary using a for loop and if conditions d. A way to create a tuple using a for loop and if conditions Answer: a

#29 What is the basic syntax of a list comprehension in Python?

Watch the Video Tutorial for the Answer: https://youtu.be/1fVckZom4K0

#python #pythonpoll #MCQsTest #yasirbhutta

a. [expression for item in list if condition] b. (expression for item in list if condition) c. {expression for item in list if condition} d. {expression while item in list if condition}

Answer: a

How can you use multiple if conditions in a list comprehension? a. [expression for item in list if condition1 and condition2] b. [expression for item in list if condition1 or condition2] c. [expression for item in list if condition1 & condition2] d. [expression for item in list if condition1 | condition2] Answer: a

Can you use a list comprehension to create a nested list in Python? a. Yes b. No Answer: a

#30 How can you create a list of squares of all even numbers in a given list using a list comprehension?

Watch the Video Tutorial for the Answer: https://youtu.be/4qy1QRTn6r4

#python #pythonpoll #MCQsTest #yasirbhutta

a. [x2 for x in list if x % 2 == 0] b. [x for x in list if x % 2 == 0]2 c. [x2 for x in list if x % 2 != 0] d. [x for x in list if x % 2 != 0]2 Answer: a

Watch this video for the answer:

Answer key (Mutiple Choice):

Fill in the Blanks

Answer Key (Fill in the Blanks):

Exercises

Review Questions

References and Bibliography