DDC-39: List comprehension to for-loop
A data challenge a day helps you master machine learning
About these daily data challenges
Each post is an exercise that helps you learn about data in Python.
Try to solve the exercise before checking my solution at the bottom of the post 🤓
You can share your solution or visualization in the comments!
Today’s challenge
The code below is a list comprehension. Figure out what it means and rewrite it using for-loops and embedded if-elif statements. Confirm that the code below and your for-loop version produce identical output.
nums = range(1,16)
[ n**2 if n%2==0 else n/2 for n in nums if n%2==0 or n>5 ].
.
.
.
Scroll down for the solution…
.
.
.
.
.
.
.
.
keep scrolling!
.
.
.
.
nums = range(1,16)
list1 = [ n**2 if n%2==0 else n/2 for n in nums if n%2==0 or n>5 ]
list2 = []
for n in nums:
# even numbers get squared
if n%2 == 0:
list2.append(n**2)
# odd numbers >5 are divided by 2
elif n>5:
list2.append(n/2)
print(list1,'\n',list2)

Hiii
# DDC-39: List comprehension to for-loop
nums = range (1,16)
results = []
for num in nums:
if num%2 ==0:
results.append (num**2)
elif (num>5 or num%2==0):
results.append(num/2)
print (results)