Skip to content

Instantly share code, notes, and snippets.

@ShyamaSankar
Created March 17, 2019 08:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ShyamaSankar/7d0d201f2623df7b09638515d9ba78d7 to your computer and use it in GitHub Desktop.
Save ShyamaSankar/7d0d201f2623df7b09638515d9ba78d7 to your computer and use it in GitHub Desktop.
List comprehension with nested if conditions
# For loop to create a list with all even multiples of 5 (nothing but multiples of 10 :/).
filtered_list = []
for number in range(1, 101):
if number % 2 == 0:
if number % 5 == 0:
filtered_list.append(number)
# Rewrite using list comprehension.
# Syntax:
# list_object = [expression_on_item for_item_in_iterable if_condition_1_on_item if_condition_2_on_item]
filtered_list = [number for number in range(1, 101) if number % 2 == 0 if number % 5 == 0]
print(filtered_list) # Output: [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment