Skip to content

Instantly share code, notes, and snippets.

@ShyamaSankar
Last active March 17, 2019 06:33
Show Gist options
  • Save ShyamaSankar/83941879d9ca4d8e41b8d12d6d57b9d9 to your computer and use it in GitHub Desktop.
Save ShyamaSankar/83941879d9ca4d8e41b8d12d6d57b9d9 to your computer and use it in GitHub Desktop.
Method within a list comprehension.
# Original list of numbers.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
def modifier(number):
"""
Returns 0 if number is a multiple of 2, 1 if number is a multiple of 3
and otherwise, the number itself.
"""
return 0 if number % 2 == 0 else 1 if number % 3 == 0 else number
# For loop to create a new list by applying 'modifier' method to a list.
modified_numbers = []
for number in numbers:
modified_numbers.append(modifier(number))
# Rewrite using list comprehension.
# Syntax:
# list_object = [method_on_item for_item_in_iterable]
modified_numbers = [modifier(number) for number in numbers]
print(modified_numbers) # Output: [1, 0, 1, 0, 5, 0, 7, 0, 1, 0]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment