List comprehensions offer a concise way to create lists in Python. Grasp the basics and nuances of this elegant construct in this short workout.
Scenario:
You’re given various Python tasks involving lists. Use list comprehensions to solve them.
Objectives:
By the end of this workout, you should be able to:
-
Understand the syntax of list comprehensions.
-
Create lists using comprehensions based on conditions and transformations.
Interactive Task:
Given the following tasks, write or identify the correct list comprehension:
-
Create a list of the squares of numbers from 1 to 10.
- Your Answer: ________________________
-
Given
words = ['apple', 'banana', 'cherry', 'date']
, use a list comprehension to create a list of words with more than 5 letters.- Your Answer: ________________________
-
Given the following list comprehension, identify its output:
[x for x in range(20) if x % 2 == 0 and x % 5 == 0]
Expected output:
-
i) [0, 10, 20]
-
ii) [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
-
iii) [0, 10]
-
iv) [2, 5, 10, 20]
-
Questions:
-
What is the main advantage of using list comprehensions in Python?
-
i) They allow for looping over multiple lists simultaneously.
-
ii) They can replace all functions in Python.
-
iii) They offer a concise and readable way to generate lists.
-
iv) They speed up the execution time of the program.
-
-
Which of the following is the correct way to use list comprehensions to get the even numbers from a list
numbers
?-
i)
[x for x in numbers if x%2]
-
ii)
[for x in numbers: if x%2==0]
-
iii)
[x for x in numbers if x%2==0]
-
iv)
for x in numbers: [x if x%2==0]
-
Duration: 15 minutes
Difficulty: Intermediate
Period:
This workout will be released on Tuesday, September 5, 2023, and will end on Thursday, September 28, 2023. But you can always come back to any of the workouts and solve them.