Created
March 17, 2019 05:10
-
-
Save ShyamaSankar/86990ee536ed8d9c82b0d01305a72514 to your computer and use it in GitHub Desktop.
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 in the original list. | |
odd_squares = [] | |
for number in numbers: | |
if number % 2 == 1: | |
odd_squares.append(number * number) | |
# Rewrite using list comprehension. | |
# Syntax: | |
# list_object = [expression_on_item for_item_in_iterable if_condition_on_item] | |
odd_squares = [number * number for number in numbers if number % 2 == 1] | |
print(odd_squares) # Output: [1, 9, 25, 49, 81] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment