Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ShyamaSankar/86990ee536ed8d9c82b0d01305a72514 to your computer and use it in GitHub Desktop.
Save ShyamaSankar/86990ee536ed8d9c82b0d01305a72514 to your computer and use it in GitHub Desktop.
# 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