Skip to content

Instantly share code, notes, and snippets.

@bbookman
Created December 27, 2018 04:19
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 bbookman/c5cf0516e9fcf0c1fdbdcff7cd43867a to your computer and use it in GitHub Desktop.
Save bbookman/c5cf0516e9fcf0c1fdbdcff7cd43867a to your computer and use it in GitHub Desktop.
Python List Comprehension: Nested
'''
Use a nested list comprehension to find all of the numbers from 1-100 that are divisible by any single digit besides 1 (2-9)
'''
#old school
no_dups = set()
for n in range(1, 100):
for x in range(2,10):
if n % x == 0:
no_dups.add(n)
print(no_dups)
print()
#nested list comprehension
result = [number for number in range(1,100) if True in [True for x in range(2,10) if number % x == 0]]
print(result)
@JohnForster
Copy link

JohnForster commented Nov 7, 2023

Just to be a smart-arse, using the full range 2-10 is unnecessary, because if a number isn't divisible by 2, it won't be divisible by 4, 6, 8 etc.

So a simplified version of this is:

result = [n for n in range(1001) if 0 in [n % divisor for divisor in [2,3,5,7]]]

@Amine-Fadssi
Copy link

Just to be a smart-arse, using the full range 2-10 is unnecessary, because if a number isn't divisible by 2, it won't be divisible by 4, 6, 8 etc.

So a simplified version of this is:

result = [n for n in range(1001) if 0 in [n % divisor for divisor in [2,3,5,7]]]

good approach.

@pawlinski
Copy link

pawlinski commented Feb 9, 2024

numbers = range(1, 1001)
div = range(2, 10)

result = [number for number in numbers if any(number % d == 0 for d in div)]

print(result)

@laurayon
Copy link

laurayon commented Mar 18, 2024

When I read the statement without looking at the 'old school' code, I understood the objective differently. This code provides a list of lists in which each sublist contains all multiples for each of the digits 2-9. In case anyone was looking for this.

nested_list = [[number for number in range(1,1001) if number%digit == 0] for digit in range(2,10)]

print(nested_list)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment