Computer Science
What is the output of the following code?
numbers = list(range(0, 51, 4))
results = []
for number in numbers:
if not number % 3:
results.append(number)
print(results)
Answer
[0, 12, 24, 36, 48]
Working
list(range(0, 51, 4)) will create a list from 0 to 48 with a step of 4 so numbers will be [0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48]. For loop will traverse the list one number at a time. if not number % 3 means if number % 3 is equal to 0 i.e. number is divisible by 3. The numbers divisible by 3 are added to the results list and after the loop results list is printed.
Related Questions
Let nums2 and nums3 be two non-empty lists. Write a Python command that will append the last element of nums3 to the end of nums2.
Consider the following code and predict the result of the following statements.
bieber = ['om', 'nom', 'nom'] counts = [1, 2, 3] nums = counts nums.append(4)
- counts is nums
- counts is add([1, 2], [3, 4])
Following code prints the given list in ascending order. Modify the code so that the elements are printed in the reverse order of the result produced by the given code.
numbers = list(range(0, 51, 4)) i = 0 while i < len(numbers): print(numbers[i] , end = " ") i += 3 # gives output as : 0 12 24 36 48
Write a program to increment the elements of a list with a number.