DEV Community

Vladimir Ignatev
Vladimir Ignatev

Posted on • Updated on

🤔 Python Quiz: Snake Comprehensions 🐍

Follow me to learn 🐍 Python in 5-minute a day fun quizzes! Find previous quiz here.

Did you know, that questions about List Comprehensions in Python are among the most popular interview question? You'll meet list comprehensions question in every test of Python proficiency no matter who you are or gonna be: engineer or data scientist!

PEP 202, titled "List Comprehensions," is a significant PEP that introduced a concise and efficient way to create lists in Python. Authored by Barry Warsaw, this PEP proposed a syntax for list comprehensions that drew inspiration from similar constructs in other programming languages like Haskell and SETL. This feature quickly became one of the most beloved aspects of the Python language for its elegance and utility, profoundly influencing Python's approach to iterable transformations and functional-style programming.

Quiz

Which code sample is done right when using list comprehensions in Python?

Sample 1

numbers = [1, 2, 3, 4, 5]
squared_numbers = [for number in numbers: number ** 2]
print(squared_numbers)
Enter fullscreen mode Exit fullscreen mode

Sample 2

numbers = [1, 2, 3, 4, 5]
squared_numbers = [number ** 2 for number in numbers]
print(squared_numbers)
Enter fullscreen mode Exit fullscreen mode

Post your answer in the comments! 0 if you think that Sample 1 is correct, 1 otherwise. As usually, the correct answer will be explained in the first comment.

Top comments (1)

Collapse
 
vladignatyev profile image
Vladimir Ignatev

The correct answer is Sample 2.

List comprehensions are a concise way to create lists in Python, as described in PEP 202. The syntax generally follows the form [expression for item in iterable]. In Sample 2, we correctly use list comprehension to create a list of squared numbers. We define the expression number ** 2 and iterate over the numbers list.

Sample 1, however, attempts to use a syntax resembling a for loop within the list comprehension, which is syntactically incorrect. The for ... in ...: syntax is not valid within list comprehensions, leading to a syntax error. The correct way, as shown in Sample 2, excludes the colon and arranges the expression before the for keyword.