w3resource

Python: Get numbers divisible by fifteen from a list using an anonymous function

Python Basic: Exercise-110 with Solution

Divisible by 15 Finder

Write a Python program to get numbers divisible by fifteen from a list using an anonymous function.

Sample Solution-1:

Python Code:

# Create a list of numbers.
num_list = [45, 55, 60, 37, 100, 105, 220]

# Use an anonymous lambda function with the filter function to filter numbers in the list that are divisible by 15.
result = list(filter(lambda x: (x % 15 == 0), num_list))

# Print the numbers that are divisible by 15.
print("Numbers divisible by 15 are", result)

Sample Output:

Numbers divisible by 15 are [45, 60, 105] 

Flowchart:

Flowchart: Get numbers divisible by fifteen from a list using an anonymous function.

Sample Solution-2:

Python Code:

# Create a list of numbers.
num_list = [45, 55, 60, 37, 100, 105, 220]

# Print the original list of numbers.
print("Original list:", num_list)

# Use an anonymous lambda function with the filter function to filter numbers in the list that are divisible by 15.
result = list(filter(lambda x: (x % 15 == 0), num_list))

# Print the numbers from the original list that are divisible by 15.
print("Numbers of the said list divisible by 15 are:", result)

Sample Output:

Original list: [45, 55, 60, 37, 100, 105, 220]
Numbers of the said list divisible by 15 are: [45, 60, 105]

Sample Solution-3:

Python Code:

# Create a list of numbers.
num_list = [45, 55, 60, 37, 100, 105, 220]

# Print the original list of numbers.
print("Original list:", num_list)

# Print a message indicating the list of numbers divisible by 15 will be displayed.
print("\nNumbers of the said list divisible by 15 are:")

# Filter the numbers in the list that are divisible by 15 using a list comprehension and a lambda function.
# Convert the resulting list to a string and join it to a single string without spaces.
result = str(''.join(filter(lambda x: x, str(list([i for i in num_list if i % 15 == 0])))))

# Print the concatenated result.
print(result)

Sample Output:

Original list: [45, 55, 60, 37, 100, 105, 220]

Numbers of the said list divisible by 15 are:
[45, 60, 105] 

Python Code Editor:

 

Previous: Write a Python program to check if a number is positive, negative or zero.
Next: Write a Python program to make file lists from current directory using a wildcard.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/python-exercises/python-basic-exercise-110.php