0
0
Pythonprogramming~10 mins

List comprehension with if–else in Python - Interactive Code Practice

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

Complete the code to create a list that doubles each number in the range 1 to 5.

Python
result = [x[1]2 for x in range(1, 6)]
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 add 2 instead of doubling.
Using '**' will square the number, not double it.
2fill in blank
medium

Complete the code to create a list that labels numbers as 'even' or 'odd' using if–else inside a list comprehension.

Python
labels = ['even' if x[1] 2 == 0 else 'odd' for x in range(1, 6)]
print(labels)
Drag options to blanks, or click blank then click option'
A%
B+
C//
D**
Attempts:
3 left
💡 Hint
Common Mistakes
Using '+' or '**' will not check divisibility.
Using '//' gives the quotient, not the remainder.
3fill in blank
hard

Fix the error in the list comprehension that should replace negative numbers with 0.

Python
numbers = [-3, 5, -1, 7]
result = [x if x [1] 0 else 0 for x in numbers]
print(result)
Drag options to blanks, or click blank then click option'
A==
B<
C>
D!=
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' will keep negative numbers instead of replacing them.
Using '==' or '!=' will not correctly filter positive numbers.
4fill in blank
hard

Fill both blanks to create a list that squares even numbers and cubes odd numbers from 1 to 5.

Python
result = [x[1]2 if x [2] 2 == 0 else x**3 for x in range(1, 6)]
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 but not square.
Using '+' instead of '%' will not check evenness.
5fill in blank
hard

Fill both blanks to create a list of strings labeling numbers as 'small', 'medium', or 'large' based on their value.

Python
sizes = ['small' if x [1] 3 else 'medium' if x [2] 6 else 'large' for x in range(1, 10)]
print(sizes)
Drag options to blanks, or click blank then click option'
A<=
B<
C>
D>=
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<=' instead of '<' changes the boundary conditions.
Using '>' or '>=' instead of '<' will misclassify numbers.