Last active
March 17, 2019 05:54
-
-
Save ShyamaSankar/59b64532762c01310c56ef4b3c0226c4 to your computer and use it in GitHub Desktop.
List comprehension with an if-else condition.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Original list of numbers. | |
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] | |
# For loop to create a list with squares of all odd numbers | |
# and doubles of all even numbers in the original list. | |
modified_numbers = [] | |
for number in numbers: | |
if number % 2 == 1: | |
modified_numbers.append(number * number) | |
else: | |
modified_numbers.append(number * 2) | |
# Rewrite using list comprehension. | |
# Syntax: | |
# list_object = [expression_1_on_item if_condition_1_on_item else expression_2_on_item for_item_in_iterable] | |
modified_numbers = [number * number if number % 2 == 1 else number * 2 for number in numbers] | |
print(modified_numbers) # Output: [1, 4, 9, 8, 25, 12, 49, 16, 81, 20] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment