0
0
Pythonprogramming~10 mins

Why list comprehension is used in Python - Test Your Understanding

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to create a list of squares from 1 to 5 using list comprehension.

Python
squares = [x[1]2 for x in range(1, 6)]
print(squares)
Drag options to blanks, or click blank then click option'
A**
B-
C+
D*
Attempts:
3 left
๐Ÿ’ก Hint
Common Mistakes
Using * instead of ** will multiply x by 2, not square it.
2fill in blank
medium

Complete the code to create a list of even numbers from 0 to 10 using list comprehension.

Python
evens = [x for x in range(11) if x [1] 2 == 0]
print(evens)
Drag options to blanks, or click blank then click option'
A%
B!=
C//
D+
Attempts:
3 left
๐Ÿ’ก Hint
Common Mistakes
Using // instead of % will do floor division, not remainder.
3fill in blank
hard

Fix the error in the list comprehension to create a list of uppercase words.

Python
words = ['apple', 'banana', 'cherry']
upper_words = [word[1] for word in words]
print(upper_words)
Drag options to blanks, or click blank then click option'
A.capitalize()
B.lower()
C.upper()
D.title()
Attempts:
3 left
๐Ÿ’ก Hint
Common Mistakes
Using .lower() will make all letters lowercase, not uppercase.
4fill in blank
hard

Fill both blanks to create a list of squares for numbers greater than 3.

Python
result = [x[1]2 for x in range(1, 7) if x [2] 3]
print(result)
Drag options to blanks, or click blank then click option'
A**
B>
C<
D*
Attempts:
3 left
๐Ÿ’ก Hint
Common Mistakes
Using * instead of ** will multiply by 2, not square.
Using < instead of > will select numbers less than 3.
5fill in blank
hard

Fill all three blanks to create a dictionary of word lengths for words longer than 4 letters.

Python
word_lengths = [1]: [1] for [2] in words if len([3]) > 4}
Drag options to blanks, or click blank then click option'
Aword
Blen(word)
Cwords
Dw
Attempts:
3 left
๐Ÿ’ก Hint
Common Mistakes
Using different variable names for keys and loop variable causes errors.
Using 'words' as loop variable is incorrect; it is the list.